[PATCH] D139170: [X86][clang] Lift _BitInt() supported max width.

2022-12-01 Thread Matthias Gehre via Phabricator via cfe-commits
mgehre-amd added a comment.

Do other targets not support > 128 bit integers, or is this PR only the first 
conservative step of lifting the limit?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139170

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


[PATCH] D139172: [clang] Mark CWG554 as N/A

2022-12-01 Thread Vlad Serebrennikov via Phabricator via cfe-commits
Endill created this revision.
Endill added a reviewer: clang-language-wg.
Herald added a project: All.
Endill requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

P1787 : //CWG554 is resolved by using the word 
“scope” instead of “declarative region”, consistent with its very common use in 
phrases like “namespace scope”.//


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D139172

Files:
  clang/test/CXX/drs/dr5xx.cpp
  clang/www/cxx_dr_status.html


Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -3366,7 +3366,7 @@
 https://wg21.link/cwg554;>554
 CD6
 Definition of declarative region and 
scope
-Unknown
+N/A
   
   
 https://wg21.link/cwg555;>555
Index: clang/test/CXX/drs/dr5xx.cpp
===
--- clang/test/CXX/drs/dr5xx.cpp
+++ clang/test/CXX/drs/dr5xx.cpp
@@ -602,6 +602,7 @@
   };
 }
 
+// dr554: na
 // dr556: na
 
 namespace dr557 { // dr557: yes


Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -3366,7 +3366,7 @@
 https://wg21.link/cwg554;>554
 CD6
 Definition of declarative region and scope
-Unknown
+N/A
   
   
 https://wg21.link/cwg555;>555
Index: clang/test/CXX/drs/dr5xx.cpp
===
--- clang/test/CXX/drs/dr5xx.cpp
+++ clang/test/CXX/drs/dr5xx.cpp
@@ -602,6 +602,7 @@
   };
 }
 
+// dr554: na
 // dr556: na
 
 namespace dr557 { // dr557: yes
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D139171: Don't revisit the subexpressions of PseudoObjectExpr when building a ParentMap

2022-12-01 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak created this revision.
ahatanak added reviewers: rjmccall, jordan_rose.
ahatanak added a project: clang.
Herald added a project: All.
ahatanak requested review of this revision.

The assertion that is removed in this patch was failing when ObjC dot notation 
expressions appear in both sides of an assignment (see the test case in 
arc-repeated-weak.mm). Visit the `PseudoObjectExpr` once when the syntactic 
expression is visited and return without visiting the subexpressions when it's 
visited again when the semantic expressions are visited.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D139171

Files:
  clang/lib/AST/ParentMap.cpp
  clang/test/SemaObjC/arc-repeated-weak.mm


Index: clang/test/SemaObjC/arc-repeated-weak.mm
===
--- clang/test/SemaObjC/arc-repeated-weak.mm
+++ clang/test/SemaObjC/arc-repeated-weak.mm
@@ -290,6 +290,18 @@
   } while(0);
 }
 
+struct S {
+  int a;
+  id b;
+};
+
+@interface C
+@property S p;
+@end
+
+void test_list_init(C *c) {
+  c.p = {0, c.p.b};
+}
 
 @interface Test (Methods)
 @end
Index: clang/lib/AST/ParentMap.cpp
===
--- clang/lib/AST/ParentMap.cpp
+++ clang/lib/AST/ParentMap.cpp
@@ -33,9 +33,11 @@
 
   switch (S->getStmtClass()) {
   case Stmt::PseudoObjectExprClass: {
-assert(OVMode == OV_Transparent && "Should not appear alongside OVEs");
 PseudoObjectExpr *POE = cast(S);
 
+if (OVMode == OV_Opaque && M[POE->getSyntacticForm()])
+  break;
+
 // If we are rebuilding the map, clear out any existing state.
 if (M[POE->getSyntacticForm()])
   for (Stmt *SubStmt : S->children())


Index: clang/test/SemaObjC/arc-repeated-weak.mm
===
--- clang/test/SemaObjC/arc-repeated-weak.mm
+++ clang/test/SemaObjC/arc-repeated-weak.mm
@@ -290,6 +290,18 @@
   } while(0);
 }
 
+struct S {
+  int a;
+  id b;
+};
+
+@interface C
+@property S p;
+@end
+
+void test_list_init(C *c) {
+  c.p = {0, c.p.b};
+}
 
 @interface Test (Methods)
 @end
Index: clang/lib/AST/ParentMap.cpp
===
--- clang/lib/AST/ParentMap.cpp
+++ clang/lib/AST/ParentMap.cpp
@@ -33,9 +33,11 @@
 
   switch (S->getStmtClass()) {
   case Stmt::PseudoObjectExprClass: {
-assert(OVMode == OV_Transparent && "Should not appear alongside OVEs");
 PseudoObjectExpr *POE = cast(S);
 
+if (OVMode == OV_Opaque && M[POE->getSyntacticForm()])
+  break;
+
 // If we are rebuilding the map, clear out any existing state.
 if (M[POE->getSyntacticForm()])
   for (Stmt *SubStmt : S->children())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D136815: [clang][Interp] Unify visiting variable declarations

2022-12-01 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 479526.
tbaeder added a comment.

Meh, just use an assert :|


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

https://reviews.llvm.org/D136815

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/ByteCodeStmtGen.cpp
  clang/lib/AST/Interp/ByteCodeStmtGen.h
  clang/lib/AST/Interp/Program.cpp
  clang/lib/AST/Interp/Program.h

Index: clang/lib/AST/Interp/Program.h
===
--- clang/lib/AST/Interp/Program.h
+++ clang/lib/AST/Interp/Program.h
@@ -79,7 +79,8 @@
   llvm::Optional getGlobal(const ValueDecl *VD);
 
   /// Returns or creates a global an creates an index to it.
-  llvm::Optional getOrCreateGlobal(const ValueDecl *VD);
+  llvm::Optional getOrCreateGlobal(const ValueDecl *VD,
+ const Expr *Init = nullptr);
 
   /// Returns or creates a dummy value for parameters.
   llvm::Optional getOrCreateDummy(const ParmVarDecl *PD);
Index: clang/lib/AST/Interp/Program.cpp
===
--- clang/lib/AST/Interp/Program.cpp
+++ clang/lib/AST/Interp/Program.cpp
@@ -124,11 +124,12 @@
   return Index;
 }
 
-llvm::Optional Program::getOrCreateGlobal(const ValueDecl *VD) {
+llvm::Optional Program::getOrCreateGlobal(const ValueDecl *VD,
+const Expr *Init) {
   if (auto Idx = getGlobal(VD))
 return Idx;
 
-  if (auto Idx = createGlobal(VD, nullptr)) {
+  if (auto Idx = createGlobal(VD, Init)) {
 GlobalIndices[VD] = *Idx;
 return Idx;
   }
@@ -156,6 +157,7 @@
 
 llvm::Optional Program::createGlobal(const ValueDecl *VD,
const Expr *Init) {
+  assert(!getGlobal(VD));
   bool IsStatic, IsExtern;
   if (auto *Var = dyn_cast(VD)) {
 IsStatic = !Var->hasLocalStorage();
Index: clang/lib/AST/Interp/ByteCodeStmtGen.h
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.h
+++ clang/lib/AST/Interp/ByteCodeStmtGen.h
@@ -65,7 +65,6 @@
   bool visitContinueStmt(const ContinueStmt *S);
 
   /// Compiles a variable declaration.
-  bool visitVarDecl(const VarDecl *VD);
 
 private:
   /// Type of the expression returned by the function.
Index: clang/lib/AST/Interp/ByteCodeStmtGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -207,7 +207,7 @@
   for (auto *D : DS->decls()) {
 // Variable declarator.
 if (auto *VD = dyn_cast(D)) {
-  if (!visitVarDecl(VD))
+  if (!this->visitVarDecl(VD))
 return false;
   continue;
 }
@@ -391,37 +391,6 @@
   return this->jump(*ContinueLabel);
 }
 
-template 
-bool ByteCodeStmtGen::visitVarDecl(const VarDecl *VD) {
-  if (!VD->hasLocalStorage()) {
-// No code generation required.
-return true;
-  }
-
-  // Integers, pointers, primitives.
-  if (Optional T = this->classify(VD->getType())) {
-const Expr *Init = VD->getInit();
-
-unsigned Offset =
-this->allocateLocalPrimitive(VD, *T, VD->getType().isConstQualified());
-// Compile the initializer in its own scope.
-if (Init) {
-  ExprScope Scope(this);
-  if (!this->visit(Init))
-return false;
-
-  return this->emitSetLocal(*T, Offset, VD);
-}
-return true;
-  }
-
-  // Composite types - allocate storage and initialize it.
-  if (Optional Offset = this->allocateLocal(VD))
-return this->visitLocalInitializer(VD->getInit(), *Offset);
-
-  return this->bail(VD);
-}
-
 namespace clang {
 namespace interp {
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -152,6 +152,8 @@
   bool visitArrayInitializer(const Expr *Initializer);
   /// Compiles a record initializer.
   bool visitRecordInitializer(const Expr *Initializer);
+  /// Creates and initializes a variable from the given decl.
+  bool visitVarDecl(const VarDecl *VD);
 
   /// Visits an expression and converts it to a boolean.
   bool visitBool(const Expr *E);
@@ -255,6 +257,12 @@
 return T->getAsCXXRecordDecl();
   }
 
+  /// Returns whether we should create a global variable for the
+  /// given VarDecl.
+  bool shouldBeGloballyIndexed(const VarDecl *VD) const {
+return VD->hasGlobalStorage() || VD->isConstexpr();
+  }
+
 protected:
   /// Variable to storage mapping.
   llvm::DenseMap Locals;
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -854,6 +854,13 @@
   PrimType Ty,
 

[PATCH] D139170: [X86][clang] Lift _BitInt() supported max width.

2022-12-01 Thread Freddy, Ye via Phabricator via cfe-commits
FreddyYe created this revision.
Herald added a project: All.
FreddyYe requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D139170

Files:
  clang/lib/Basic/Targets/X86.h
  clang/test/CodeGen/ext-int-cc.c
  clang/test/Lexer/bitint-constants.c
  clang/test/Preprocessor/cuda-types.cu
  clang/test/Sema/large-bit-int.c
  clang/test/SemaCXX/ext-int.cpp

Index: clang/test/SemaCXX/ext-int.cpp
===
--- clang/test/SemaCXX/ext-int.cpp
+++ clang/test/SemaCXX/ext-int.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s -Wimplicit-int-conversion -Wno-unused -Wunevaluated-expression -triple x86_64-gnu-linux
+// RUN: %clang_cc1 -fsyntax-only -verify %s -Wimplicit-int-conversion -Wno-unused -Wunevaluated-expression -triple aarch64-unknown-unknown
 
 template
 struct HasExtInt {
Index: clang/test/Sema/large-bit-int.c
===
--- clang/test/Sema/large-bit-int.c
+++ clang/test/Sema/large-bit-int.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fexperimental-max-bitint-width=1024 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple aarch64-unknown-unknown -fexperimental-max-bitint-width=1024 -fsyntax-only -verify %s
 
 void f() {
   _Static_assert(__BITINT_MAXWIDTH__ == 1024, "Macro value is unexpected.");
Index: clang/test/Preprocessor/cuda-types.cu
===
--- clang/test/Preprocessor/cuda-types.cu
+++ clang/test/Preprocessor/cuda-types.cu
@@ -1,6 +1,6 @@
 // Check that types, widths, __CLANG_ATOMIC* macros, etc. match on the host and
-// device sides of CUDA compilations.  Note that we filter out long double, as
-// this is intentionally different on host and device.
+// device sides of CUDA compilations. Note that we filter out long double and
+// maxwidth of _BitInt(), as this is intentionally different on host and device.
 //
 // Also ignore __CLANG_ATOMIC_LLONG_LOCK_FREE on i386. The default host CPU for
 // an i386 triple is typically at least an i586, which has cmpxchg8b (Clang
@@ -14,40 +14,40 @@
 
 // RUN: %clang --cuda-host-only -nocudainc -target i386-unknown-linux-gnu -x cuda -E -dM -o - /dev/null \
 // RUN:   | grep -E 'define __[^ ]*(TYPE|MAX|SIZEOF|WIDTH)|define __CLANG_ATOMIC' \
-// RUN:   | grep -Ev '__LDBL|_LONG_DOUBLE|_ATOMIC_LLONG_LOCK_FREE' > %t/i386-host-defines-filtered
+// RUN:   | grep -Ev '__LDBL|_LONG_DOUBLE|BITINT_MAXWIDTH|_ATOMIC_LLONG_LOCK_FREE' > %t/i386-host-defines-filtered
 // RUN: %clang --cuda-device-only -nocudainc -nocudalib -target i386-unknown-linux-gnu -x cuda -E -dM -o - /dev/null \
 // RUN:   | grep -E 'define __[^ ]*(TYPE|MAX|SIZEOF|WIDTH)|define __CLANG_ATOMIC' \
-// RUN:   | grep -Ev '__LDBL|_LONG_DOUBLE|_ATOMIC_LLONG_LOCK_FREE' > %t/i386-device-defines-filtered
+// RUN:   | grep -Ev '__LDBL|_LONG_DOUBLE|BITINT_MAXWIDTH|_ATOMIC_LLONG_LOCK_FREE' > %t/i386-device-defines-filtered
 // RUN: diff %t/i386-host-defines-filtered %t/i386-device-defines-filtered
 
 // RUN: %clang --cuda-host-only -nocudainc -target x86_64-unknown-linux-gnu -x cuda -E -dM -o - /dev/null \
 // RUN:   | grep -E 'define __[^ ]*(TYPE|MAX|SIZEOF|WIDTH)|define __CLANG_ATOMIC' \
-// RUN:   | grep -Ev '__LDBL|_LONG_DOUBLE' > %t/x86_64-host-defines-filtered
+// RUN:   | grep -Ev '__LDBL|_LONG_DOUBLE|BITINT_MAXWIDTH' > %t/x86_64-host-defines-filtered
 // RUN: %clang --cuda-device-only -nocudainc -nocudalib -target x86_64-unknown-linux-gnu -x cuda -E -dM -o - /dev/null \
 // RUN:   | grep -E 'define __[^ ]*(TYPE|MAX|SIZEOF|WIDTH)|define __CLANG_ATOMIC' \
-// RUN:   | grep -Ev '__LDBL|_LONG_DOUBLE' > %t/x86_64-device-defines-filtered
+// RUN:   | grep -Ev '__LDBL|_LONG_DOUBLE|BITINT_MAXWIDTH' > %t/x86_64-device-defines-filtered
 // RUN: diff %t/x86_64-host-defines-filtered %t/x86_64-device-defines-filtered
 
 // RUN: %clang --cuda-host-only -nocudainc -target powerpc64-unknown-linux-gnu -x cuda -E -dM -o - /dev/null \
 // RUN:   | grep -E 'define __[^ ]*(TYPE|MAX|SIZEOF|WIDTH)|define __CLANG_ATOMIC' \
-// RUN:   | grep -Ev '__LDBL|_LONG_DOUBLE' > %t/powerpc64-host-defines-filtered
+// RUN:   | grep -Ev '__LDBL|_LONG_DOUBLE|BITINT_MAXWIDTH' > %t/powerpc64-host-defines-filtered
 // RUN: %clang --cuda-device-only -nocudainc -nocudalib -target powerpc64-unknown-linux-gnu -x cuda -E -dM -o - /dev/null \
 // RUN:   | grep -E 'define __[^ ]*(TYPE|MAX|SIZEOF|WIDTH)|define __CLANG_ATOMIC' \
-// RUN:   | grep -Ev '__LDBL|_LONG_DOUBLE' > %t/powerpc64-device-defines-filtered
+// RUN:   | grep -Ev '__LDBL|_LONG_DOUBLE|BITINT_MAXWIDTH' > %t/powerpc64-device-defines-filtered
 // RUN: diff %t/powerpc64-host-defines-filtered %t/powerpc64-device-defines-filtered
 
 // RUN: %clang --cuda-host-only -nocudainc -target i386-windows-msvc -x cuda -E -dM -o - /dev/null \
 // RUN:   | grep -E 'define __[^ ]*(TYPE|MAX|SIZEOF|WIDTH)|define 

[clang] 67f3405 - Revert "[clang][modules][deps] Parent module maps are affecting"

2022-12-01 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-12-01T21:39:51-08:00
New Revision: 67f34054d6ea8e40fd10cb74441d5ccab004c75b

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

LOG: Revert "[clang][modules][deps] Parent module maps are affecting"

This reverts commit f99e5a9106f08ad92a22c3b114d2052e5c502924.

Added: 


Modified: 
clang/lib/Serialization/ASTWriter.cpp

Removed: 
clang/test/ClangScanDeps/modules-extern-submodule.c



diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 1f5de568b3ba..80930357a6d1 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -192,11 +192,10 @@ std::set GetAffectingModuleMaps(const 
HeaderSearch ,
 
   const ModuleMap  = HS.getModuleMap();
 
-  auto ProcessModuleOnce = [&](const Module *M) {
-for (const Module *Mod = M; Mod; Mod = Mod->Parent)
-  if (ProcessedModules.insert(Mod).second)
-if (auto ModuleMapFile = MM.getModuleMapFileForUniquing(Mod))
-  ModuleMaps.insert(*ModuleMapFile);
+  auto ProcessModuleOnce = [&](const Module *Mod) {
+if (ProcessedModules.insert(Mod).second)
+  if (auto ModuleMapFile = MM.getModuleMapFileForUniquing(Mod))
+ModuleMaps.insert(*ModuleMapFile);
   };
 
   for (const Module *CurrentModule : ModulesToProcess) {

diff  --git a/clang/test/ClangScanDeps/modules-extern-submodule.c 
b/clang/test/ClangScanDeps/modules-extern-submodule.c
deleted file mode 100644
index bf1d41c1c2b0..
--- a/clang/test/ClangScanDeps/modules-extern-submodule.c
+++ /dev/null
@@ -1,128 +0,0 @@
-// RUN: rm -rf %t
-// RUN: split-file %s %t
-
-//--- tu.m
-@import first;
-
-//--- first/first/module.modulemap
-module first { header "first.h" }
-//--- first/first/first.h
-#include 
-
-//--- second/second/module.modulemap
-module second { extern module sub "sub.modulemap" }
-//--- second/second/sub.modulemap
-module second.sub { header "sub.h" }
-//--- second/second/sub.h
-@import third;
-
-//--- third/module.modulemap
-module third {}
-
-//--- cdb.json.template
-[{
-  "file": "DIR/tu.c",
-  "directory": "DIR",
-  "command": "clang -I DIR/first -I DIR/second -I DIR/third -fmodules 
-fmodules-cache-path=DIR/cache -c DIR/tu.m -o DIR/tu.o"
-}]
-
-// RUN: sed "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
-// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full > %t/result.json
-// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
-
-// CHECK:   {
-// CHECK-NEXT:   "modules": [
-// CHECK-NEXT: {
-// CHECK-NEXT:   "clang-module-deps": [
-// CHECK-NEXT: {
-// CHECK-NEXT:   "context-hash": "{{.*}}",
-// CHECK-NEXT:   "module-name": "second"
-// CHECK-NEXT: }
-// CHECK-NEXT:   ],
-// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/first/first/module.modulemap",
-// CHECK-NEXT:   "command-line": [
-// CHECK-NEXT: "-cc1",
-// CHECK:  
"-fmodule-map-file=[[PREFIX]]/second/second/module.modulemap"
-// CHECK-NOT:  
"-fmodule-map-file=[[PREFIX]]/second/second/sub.modulemap"
-// CHECK-NOT:  "-fmodule-map-file=[[PREFIX]]/third/module.modulemap"
-// CHECK:  
"-fmodule-file=second=[[PREFIX]]/cache/{{.*}}/second-{{.*}}.pcm"
-// CHECK:],
-// CHECK-NEXT:   "context-hash": "{{.*}}",
-// CHECK-NEXT:   "file-deps": [
-// CHECK-NEXT: "[[PREFIX]]/first/first/first.h",
-// CHECK-NEXT: "[[PREFIX]]/first/first/module.modulemap",
-// CHECK-NEXT: "[[PREFIX]]/second/second/module.modulemap",
-// CHECK-NEXT: "[[PREFIX]]/second/second/sub.modulemap"
-// CHECK-NEXT:   ],
-// CHECK-NEXT:   "name": "first"
-// CHECK-NEXT: },
-// CHECK-NEXT: {
-// CHECK-NEXT:   "clang-module-deps": [
-// CHECK-NEXT: {
-// CHECK-NEXT:   "context-hash": "{{.*}}",
-// CHECK-NEXT:   "module-name": "third"
-// CHECK-NEXT: }
-// CHECK-NEXT:   ],
-// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/second/second/module.modulemap",
-// CHECK-NEXT:   "command-line": [
-// CHECK-NEXT: "-cc1",
-// CHECK:  "-fmodule-map-file=[[PREFIX]]/third/module.modulemap",
-// CHECK:  
"-fmodule-file=third=[[PREFIX]]/cache/{{.*}}/third-{{.*}}.pcm",
-// CHECK:],
-// CHECK-NEXT:   "context-hash": "{{.*}}",
-// CHECK-NEXT:   "file-deps": [
-// CHECK-NEXT: "[[PREFIX]]/second/second/module.modulemap",
-// CHECK-NEXT: "[[PREFIX]]/second/second/sub.h",
-// CHECK-NEXT: "[[PREFIX]]/second/second/sub.modulemap",
-// CHECK-NEXT: "[[PREFIX]]/third/module.modulemap"
-// CHECK-NEXT:   ],
-// CHECK-NEXT:   "name": "second"
-// CHECK-NEXT: },
-// 

[clang] f0ce827 - Revert "[clang][modules][deps] Including module maps are affecting"

2022-12-01 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-12-01T21:39:51-08:00
New Revision: f0ce827c6972009c5052f8447c6aadf4e4be6113

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

LOG: Revert "[clang][modules][deps] Including module maps are affecting"

This reverts commit 83973cf157f7850eb133a4bbfa0f8b7958bad215.

Added: 


Modified: 
clang/lib/Serialization/ASTWriter.cpp

Removed: 
clang/test/ClangScanDeps/modules-extern-unrelated.m



diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 458e88d3688d..1f5de568b3ba 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -161,14 +161,12 @@ static TypeCode getTypeCodeForTypeClass(Type::TypeClass 
id) {
 
 namespace {
 
-std::set GetAffectingModuleMaps(const Preprocessor ,
+std::set GetAffectingModuleMaps(const HeaderSearch ,
Module *RootModule) {
   std::set ModuleMaps{};
   std::set ProcessedModules;
   SmallVector ModulesToProcess{RootModule};
 
-  const HeaderSearch  = PP.getHeaderSearchInfo();
-
   SmallVector FilesByUID;
   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
 
@@ -193,27 +191,12 @@ std::set GetAffectingModuleMaps(const 
Preprocessor ,
   }
 
   const ModuleMap  = HS.getModuleMap();
-  SourceManager  = PP.getSourceManager();
-
-  auto ForIncludeChain = [&](FileEntryRef F,
- llvm::function_ref CB) {
-CB(F);
-FileID FID = SourceMgr.translateFile(F);
-SourceLocation Loc = SourceMgr.getIncludeLoc(FID);
-while (Loc.isValid()) {
-  FID = SourceMgr.getFileID(Loc);
-  CB(*SourceMgr.getFileEntryRefForID(FID));
-  Loc = SourceMgr.getIncludeLoc(FID);
-}
-  };
 
   auto ProcessModuleOnce = [&](const Module *M) {
 for (const Module *Mod = M; Mod; Mod = Mod->Parent)
   if (ProcessedModules.insert(Mod).second)
 if (auto ModuleMapFile = MM.getModuleMapFileForUniquing(Mod))
-  ForIncludeChain(*ModuleMapFile, [&](FileEntryRef F) {
-ModuleMaps.insert(F);
-  });
+  ModuleMaps.insert(*ModuleMapFile);
   };
 
   for (const Module *CurrentModule : ModulesToProcess) {
@@ -4562,7 +4545,8 @@ void ASTWriter::collectNonAffectingInputFiles() {
   if (!WritingModule)
 return;
 
-  auto AffectingModuleMaps = GetAffectingModuleMaps(*PP, WritingModule);
+  auto AffectingModuleMaps =
+  GetAffectingModuleMaps(PP->getHeaderSearchInfo(), WritingModule);
 
   unsigned FileIDAdjustment = 0;
   unsigned OffsetAdjustment = 0;

diff  --git a/clang/test/ClangScanDeps/modules-extern-unrelated.m 
b/clang/test/ClangScanDeps/modules-extern-unrelated.m
deleted file mode 100644
index bcdd822e3e4e..
--- a/clang/test/ClangScanDeps/modules-extern-unrelated.m
+++ /dev/null
@@ -1,135 +0,0 @@
-// RUN: rm -rf %t
-// RUN: split-file %s %t
-
-//--- tu.m
-@import zeroth;
-
-//--- zeroth/module.modulemap
-module zeroth { header "zeroth.h" }
-//--- zeroth/zeroth.h
-@import first;
-#include "second.h"
-
-//--- first/module.modulemap
-module first {}
-module first_other { header "first_other.h" }
-//--- first/first_other.h
-
-//--- second/module.modulemap
-extern module second "second.modulemap"
-//--- second/second.modulemap
-module second { header "second.h" }
-//--- second/second.h
-#include "first_other.h"
-
-//--- cdb.json.template
-[{
-  "directory": "DIR",
-  "file": "DIR/tu.m",
-  "command": "clang -fmodules -fmodules-cache-path=DIR/cache -I DIR/zeroth -I 
DIR/first -I DIR/second -c DIR/tu.m -o DIR/tu.o"
-}]
-
-// RUN: sed -e "s|DIR|%/t|g" -e "s|INPUTS|%/S/Inputs|g" %t/cdb.json.template > 
%t/cdb.json
-// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full > %t/result.json
-// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
-
-// CHECK:  {
-// CHECK-NEXT:   "modules": [
-// CHECK-NEXT: {
-// CHECK-NEXT:   "clang-module-deps": [],
-// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/first/module.modulemap",
-// CHECK-NEXT:   "command-line": [
-// CHECK:],
-// CHECK-NEXT:   "context-hash": "{{.*}}",
-// CHECK-NEXT:   "file-deps": [
-// CHECK-NEXT: "[[PREFIX]]/first/module.modulemap"
-// CHECK-NEXT:   ],
-// CHECK-NEXT:   "name": "first"
-// CHECK-NEXT: },
-// CHECK-NEXT: {
-// CHECK-NEXT:   "clang-module-deps": [],
-// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/first/module.modulemap",
-// CHECK-NEXT:   "command-line": [
-// CHECK:],
-// CHECK-NEXT:   "context-hash": "{{.*}}",
-// CHECK-NEXT:   "file-deps": [
-// CHECK-NEXT: "[[PREFIX]]/first/first_other.h",
-// CHECK-NEXT: "[[PREFIX]]/first/module.modulemap"
-// CHECK-NEXT:   ],
-// 

[PATCH] D137534: [C++20] [Modules] [ClangScanDeps] Allow clang-scan-deps to without specified compilation database in P1689 (3/3)

2022-12-01 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

In D137534#3965012 , @ben.boeckel 
wrote:

> So a few things I see when trying to put this into CMake:
>
> - P1689  output is only to `stdout`?
> - Is there a way to get `-MF` output for the files read during scanning? This 
> is useful to know that "header X changed, scanning may have changed, so 
> please rerun scanning".
>
> Other than that, I have success with CMake's test suite with this patchset as 
> well as the patchset of D137059 .

Great to hear that!

> - P1689  output is only to `stdout`?

From the current implementation, it looks true that the output of 
clang-scan-deps is only to stdout. I guess it may not be problem since we can 
redirect it to the file we want. Or is it necessary to specify an output file 
in the flags?

> Is there a way to get `-MF` output for the files read during scanning? This 
> is useful to know that "header X changed, scanning may have changed, so 
> please rerun scanning".

I sent https://reviews.llvm.org/D139168 to address. You can specify the output 
of `-MF` in `--p1689-makeformat-output=` flags. Is this satisfying?


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

https://reviews.llvm.org/D137534

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


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

2022-12-01 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu created this revision.
ChuanqiXu added reviewers: ben.boeckel, Bigcheese, jansvoboda11.
Herald added a project: All.
ChuanqiXu requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Required in https://reviews.llvm.org/D137534.

The build systems needs the information to know that "header X changed, 
scanning may have changed, so please rerun scanning". Although it is possible 
to get the information by running clang-scan-deps for the second time with make 
format, it is not user friendly clearly.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D139168

Files:
  clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
  clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
  clang/test/ClangScanDeps/P1689.cppm
  clang/tools/clang-scan-deps/ClangScanDeps.cpp

Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -187,6 +187,13 @@
"dependencies are to be computed."),
 llvm::cl::cat(DependencyScannerCategory));
 
+llvm::cl::opt P1689MakeformatOutputpath(
+"p1689-makeformat-output", llvm::cl::Optional,
+llvm::cl::desc("Only supported for P1689. Print the make-style dependency "
+   "output to the specified output. This is a helper for build "
+   "systems to do duplicate scanning."),
+llvm::cl::cat(DependencyScannerCategory));
+
 llvm::cl::opt P1689TargettedCommand(
 llvm::cl::Positional, llvm::cl::ZeroOrMore,
 llvm::cl::desc("The command line flags for the target of which "
@@ -584,6 +591,19 @@
   return std::move(FixedCompilationDatabase);
 }
 
+static raw_ostream () {
+  if (!P1689MakeformatOutputpath.empty()) {
+std::error_code EC;
+static llvm::raw_fd_ostream OS(P1689MakeformatOutputpath, EC);
+if (EC)
+  llvm::errs() << "Failed to open P1689 make format output file \""
+   << P1689MakeformatOutputpath << "\" for " << EC.message()
+   << "\n";
+return OS;
+  }
+  return llvm::outs();
+}
+
 int main(int argc, const char **argv) {
   std::string ErrorMessage;
   std::unique_ptr Compilations =
@@ -662,7 +682,7 @@
 
   SharedStream Errs(llvm::errs());
   // Print out the dependency results to STDOUT by default.
-  SharedStream DependencyOS(llvm::outs());
+  SharedStream DependencyOS(getDependencyOS());
 
   DependencyScanningService Service(ScanMode, Format, OptimizeArgs,
 EagerLoadModules);
@@ -722,10 +742,20 @@
  Errs))
 HadErrors = true;
 } else if (Format == ScanningOutputFormat::P1689) {
+  llvm::Optional MakeformatOutput;
+  if (!P1689MakeformatOutputpath.empty())
+MakeformatOutput.emplace();
+
   auto MaybeRule = WorkerTools[I]->getP1689ModuleDependencyFile(
-  *Input, CWD, MaybeModuleName);
-  if (handleP1689DependencyToolResult(Filename, MaybeRule, PD, Errs))
-HadErrors = true;
+  *Input, CWD, MakeformatOutput, MaybeModuleName);
+  HadErrors =
+  handleP1689DependencyToolResult(Filename, MaybeRule, PD, Errs);
+
+  if (MakeformatOutput && !MakeformatOutput->empty() && !HadErrors) {
+llvm::Expected MaybeOutput(*MakeformatOutput);
+HadErrors = handleMakeDependencyToolResult(Filename, MaybeOutput,
+   DependencyOS, Errs);
+  }
 } else if (DeprecatedDriverCommand) {
   auto MaybeFullDeps =
   WorkerTools[I]->getFullDependenciesLegacyDriverCommand(
Index: clang/test/ClangScanDeps/P1689.cppm
===
--- clang/test/ClangScanDeps/P1689.cppm
+++ clang/test/ClangScanDeps/P1689.cppm
@@ -22,6 +22,14 @@
 // RUN: clang-scan-deps -format=p1689 --p1689-targeted-file-name=%t/User.cpp --p1689-targeted-output=%t/User.o \
 // RUN:   -- -std=c++20 -c \
 // RUN:   | FileCheck %t/User.cpp -DPREFIX=%/t
+//
+// Check we can generate the make-style dependencies as expected.
+// RUN: clang-scan-deps --compilation-database %t/P1689.json -format=p1689 --p1689-makeformat-output=%t/P1689.dep
+// RUN: cat %t/P1689.dep | FileCheck %t/Checks.cpp -DPREFIX=%/t --check-prefix=CHECK-MAKE
+//
+// RUN: clang-scan-deps -format=p1689 --p1689-targeted-file-name=%t/impl_part.cppm --p1689-targeted-output=%t/impl_part.o \
+// RUN:   --p1689-makeformat-output=%t/impl_part.dep -- -std=c++20 -c
+// RUN: cat %t/impl_part.dep | FileCheck %t/impl_part.cppm -DPREFIX=%/t --check-prefix=CHECK-MAKE
 
 //--- P1689.json.in
 [
@@ -57,7 +65,6 @@
 }
 ]
 
-
 //--- M.cppm
 export module M;
 export import :interface_part;
@@ -145,6 +152,10 @@
 // CHECK-NEXT:   "version": 1
 // CHECK-NEXT: }
 

[clang] 8ab388e - [clang][deps] Convert file dependency paths to the native style

2022-12-01 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-12-01T21:07:56-08:00
New Revision: 8ab388e158528d9af5eb0376ef698b243d946f19

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

LOG: [clang][deps] Convert file dependency paths to the native style

This is an attempt to fix a Windows bot failure. In the test introduced in 
83973cf1, file dependencies were printed out-of-order (after replacing 
backslashes with slashes). This might've been caused by styles of some paths 
being different.

Added: 


Modified: 
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp

Removed: 




diff  --git a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp 
b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
index 93720f73ce9b0..9e84d9547db16 100644
--- a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -580,23 +580,24 @@ bool ModuleDepCollector::isPrebuiltModule(const Module 
*M) {
   return true;
 }
 
-static StringRef makeAbsolute(CompilerInstance , StringRef Path,
-  SmallVectorImpl ) {
+static StringRef makeAbsoluteAndPreferred(CompilerInstance , StringRef Path,
+  SmallVectorImpl ) {
   if (llvm::sys::path::is_absolute(Path))
 return Path;
   Storage.assign(Path.begin(), Path.end());
   CI.getFileManager().makeAbsolutePath(Storage);
+  llvm::sys::path::make_preferred(Storage);
   return StringRef(Storage.data(), Storage.size());
 }
 
 void ModuleDepCollector::addFileDep(StringRef Path) {
   llvm::SmallString<256> Storage;
-  Path = makeAbsolute(ScanInstance, Path, Storage);
+  Path = makeAbsoluteAndPreferred(ScanInstance, Path, Storage);
   FileDeps.push_back(std::string(Path));
 }
 
 void ModuleDepCollector::addFileDep(ModuleDeps , StringRef Path) {
   llvm::SmallString<256> Storage;
-  Path = makeAbsolute(ScanInstance, Path, Storage);
+  Path = makeAbsoluteAndPreferred(ScanInstance, Path, Storage);
   MD.FileDeps.insert(Path);
 }



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


[PATCH] D85802: [clang] Add -fc++-abi= flag for specifying which C++ ABI to use

2022-12-01 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

So, some context for how this came up/what I'm trying to address:

So I started here: D117616  (for the googlers 
playing at home, see: b/198958855 for the proximal motivation) - not packing 
non-POD members of packed structs.
That lead to D119051  (changing the Itanium 
definition of POD to allow defaulted special member functions, to match GCC)
Which included a discussion  about 
where to implement this property (`areDefaultedSMFStillPOD`) - I guess I had it 
in `TargetInfo` initially, @rnk asked about whether I could move a related 
query (`getTailPaddingUseRules`) from `TargetCXXInfo` to `TargetInfo` to keep 
related things together.
I tried that refactor in D135326 , chatted 
with @rjmccall about the TargetCXXABI abstraction and we were both 
confused/didn't know why the `-fcxx-abi` flag exists, though in favor of the 
TargetCXXABI abstraction existing, so that at least some things don't need to 
be duplicated between targets, but not that it should be varied within an 
operating system.
Which got me to this discussion here.

So these configurable dimensions are adding friction to development and risk 
targets not getting the ABI they probably want (for instance, Fuchsia's 
probably missed these GCC ABI fixes related to POD/packing). It's unclear which 
C++ ABI things need to go in the TargetCXXABI versus all the other stuff that's 
implemented in ItaniumCXXABI/MicrosoftCXXABI, etc. Though perhaps that can be 
addressed anyway, regardless of whether it's variable within an OS - though the 
latter does add to the confusion.

The way I'd picture this, with what I know at the moment, is that TargetCXXABI 
is only the parts of the ABI that are necessary during parsing (which explains 
why Itanium/MicrosoftCXXABI in clangCodeGen don't come up here - they're 
exclusive to codegen/don't impact the AST), and could be implemented as mixins 
to TargetInfo - different TargetInfos could inheret from different CXXABIs, but 
I guess they could compose to support this CXXABI-varying-within-OS, but 
complicates the interactions with the codegen CXXABI abstractions, I think.

It's awkward, I think, to have TargetCXXABI sort of have an ad-hoc target/abi 
enum inside it anyway - and maybe would be nice if it used inheritance/virtual 
functions the same as TargetInfo does. We could have an ItaniumTargetCXXABI 
that is whatever the purest form of that is we have at the moment, and parts 
could be overridden by targets that want particular subsets/old versions of 
that - though perhaps it'll be simple enough to say ClangVersionTargetCXXABI 
derives from ItaniumTargetCXXABI and overrides the few things based on the 
clang cxx-abi-version flag...

My understanding of the fuchsia situation is that there's a clang compiled 
project and the fuchsia floating ABI, but then a desire to build some code with 
GCC that doesn't implement that ABI - but GCC can't build everything (libc++ in 
particular) so you need to build that with clang, but targeting the GCC ABI. I 
would think/hope the way to address that would be to tell Clang you're 
targeting whatever OS GCC is targeting (though if I understand correctly that's 
a bit of a pain having to specify all the library paths, etc, from scratch like 
you have to do for GCC? But hopefully if you can do it for GCC you can do it 
for Clang in a similar way?). This might remove the need for Clang to support 
this use case & simplify Clang's already fairly complicated ABI handling & 
reduce the chance of divergence/ABI bugs being introduced to this complicated 
matrix of compatibility.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D85802

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


[PATCH] D138702: support for HIP non hostcall printf

2022-12-01 Thread Vikram Hegde via Phabricator via cfe-commits
vikramRH added a comment.

There were some issues reported where it was found that pcie atomics are not 
available in some environments, as a result hostcall and HIP-Printf were also 
not available. This Patch is intended to provide an alternative in such 
scenarios while hostcall based implementation remains the primary option.

After discussions with Sameer, I am convinced that it is better to do this 
transformation at clang CodeGen phase rather than a opt pass (similar to 
current hostcall based implementation),
Hence this patch needs rework and I shall include the review comments in the 
updated patch. (I agree on the option too, I shall think of a option name with 
a named argument)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138702

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


[PATCH] D139148: Fix nullptr dereference found by Coverity static analysis tool

2022-12-01 Thread Sindhu Chittireddy via Phabricator via cfe-commits
schittir added a comment.

In D139148#3965404 , @shafik wrote:

> This looks like the correct thing to do but I see further down there are also 
> unconditional uses of `Initializer` that should also be guarded with a check. 
> It would be good to fix those as well since we are here.

Yes, it does make sense.

> I am guessing the answer is no since this was found using a static analysis 
> tool but do you have a test case that triggers this failure?

Indeed, the answer is no.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139148

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


[PATCH] D137206: [clang][modules][deps] Including module maps are affecting

2022-12-01 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG83973cf157f7: [clang][modules][deps] Including module maps 
are affecting (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D137206?vs=472445=479517#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137206

Files:
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/ClangScanDeps/modules-extern-unrelated.m

Index: clang/test/ClangScanDeps/modules-extern-unrelated.m
===
--- /dev/null
+++ clang/test/ClangScanDeps/modules-extern-unrelated.m
@@ -0,0 +1,135 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+//--- tu.m
+@import zeroth;
+
+//--- zeroth/module.modulemap
+module zeroth { header "zeroth.h" }
+//--- zeroth/zeroth.h
+@import first;
+#include "second.h"
+
+//--- first/module.modulemap
+module first {}
+module first_other { header "first_other.h" }
+//--- first/first_other.h
+
+//--- second/module.modulemap
+extern module second "second.modulemap"
+//--- second/second.modulemap
+module second { header "second.h" }
+//--- second/second.h
+#include "first_other.h"
+
+//--- cdb.json.template
+[{
+  "directory": "DIR",
+  "file": "DIR/tu.m",
+  "command": "clang -fmodules -fmodules-cache-path=DIR/cache -I DIR/zeroth -I DIR/first -I DIR/second -c DIR/tu.m -o DIR/tu.o"
+}]
+
+// RUN: sed -e "s|DIR|%/t|g" -e "s|INPUTS|%/S/Inputs|g" %t/cdb.json.template > %t/cdb.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full > %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
+
+// CHECK:  {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file": "[[PREFIX]]/first/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/first/module.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "first"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file": "[[PREFIX]]/first/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/first/first_other.h",
+// CHECK-NEXT: "[[PREFIX]]/first/module.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "first_other"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "module-name": "first_other"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "clang-modulemap-file": "[[PREFIX]]/second/second.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/first/module.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/second/second.h",
+// CHECK-NEXT: "[[PREFIX]]/second/second.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "second"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "module-name": "first"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "module-name": "second"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "clang-modulemap-file": "[[PREFIX]]/zeroth/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/first/module.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/second/module.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/second/second.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/zeroth/module.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/zeroth/zeroth.h"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "zeroth"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "translation-units": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "commands": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-context-hash": "{{.*}}",
+// CHECK-NEXT:   "clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "module-name": "zeroth"
+// CHECK-NEXT: }
+// 

[clang] 83973cf - [clang][modules][deps] Including module maps are affecting

2022-12-01 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-12-01T20:16:17-08:00
New Revision: 83973cf157f7850eb133a4bbfa0f8b7958bad215

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

LOG: [clang][modules][deps] Including module maps are affecting

With this patch, we mark module maps that include an affecting `extern` module 
map as also affecting. This is a generalization of D137197: now we don't 
require the importing module map to describe parent of the extern module.

Depends on D137198.

Reviewed By: Bigcheese

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

Added: 
clang/test/ClangScanDeps/modules-extern-unrelated.m

Modified: 
clang/lib/Serialization/ASTWriter.cpp

Removed: 




diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 1f5de568b3ba..458e88d3688d 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -161,12 +161,14 @@ static TypeCode getTypeCodeForTypeClass(Type::TypeClass 
id) {
 
 namespace {
 
-std::set GetAffectingModuleMaps(const HeaderSearch ,
+std::set GetAffectingModuleMaps(const Preprocessor ,
Module *RootModule) {
   std::set ModuleMaps{};
   std::set ProcessedModules;
   SmallVector ModulesToProcess{RootModule};
 
+  const HeaderSearch  = PP.getHeaderSearchInfo();
+
   SmallVector FilesByUID;
   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
 
@@ -191,12 +193,27 @@ std::set GetAffectingModuleMaps(const 
HeaderSearch ,
   }
 
   const ModuleMap  = HS.getModuleMap();
+  SourceManager  = PP.getSourceManager();
+
+  auto ForIncludeChain = [&](FileEntryRef F,
+ llvm::function_ref CB) {
+CB(F);
+FileID FID = SourceMgr.translateFile(F);
+SourceLocation Loc = SourceMgr.getIncludeLoc(FID);
+while (Loc.isValid()) {
+  FID = SourceMgr.getFileID(Loc);
+  CB(*SourceMgr.getFileEntryRefForID(FID));
+  Loc = SourceMgr.getIncludeLoc(FID);
+}
+  };
 
   auto ProcessModuleOnce = [&](const Module *M) {
 for (const Module *Mod = M; Mod; Mod = Mod->Parent)
   if (ProcessedModules.insert(Mod).second)
 if (auto ModuleMapFile = MM.getModuleMapFileForUniquing(Mod))
-  ModuleMaps.insert(*ModuleMapFile);
+  ForIncludeChain(*ModuleMapFile, [&](FileEntryRef F) {
+ModuleMaps.insert(F);
+  });
   };
 
   for (const Module *CurrentModule : ModulesToProcess) {
@@ -4545,8 +4562,7 @@ void ASTWriter::collectNonAffectingInputFiles() {
   if (!WritingModule)
 return;
 
-  auto AffectingModuleMaps =
-  GetAffectingModuleMaps(PP->getHeaderSearchInfo(), WritingModule);
+  auto AffectingModuleMaps = GetAffectingModuleMaps(*PP, WritingModule);
 
   unsigned FileIDAdjustment = 0;
   unsigned OffsetAdjustment = 0;

diff  --git a/clang/test/ClangScanDeps/modules-extern-unrelated.m 
b/clang/test/ClangScanDeps/modules-extern-unrelated.m
new file mode 100644
index ..bcdd822e3e4e
--- /dev/null
+++ b/clang/test/ClangScanDeps/modules-extern-unrelated.m
@@ -0,0 +1,135 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+//--- tu.m
+@import zeroth;
+
+//--- zeroth/module.modulemap
+module zeroth { header "zeroth.h" }
+//--- zeroth/zeroth.h
+@import first;
+#include "second.h"
+
+//--- first/module.modulemap
+module first {}
+module first_other { header "first_other.h" }
+//--- first/first_other.h
+
+//--- second/module.modulemap
+extern module second "second.modulemap"
+//--- second/second.modulemap
+module second { header "second.h" }
+//--- second/second.h
+#include "first_other.h"
+
+//--- cdb.json.template
+[{
+  "directory": "DIR",
+  "file": "DIR/tu.m",
+  "command": "clang -fmodules -fmodules-cache-path=DIR/cache -I DIR/zeroth -I 
DIR/first -I DIR/second -c DIR/tu.m -o DIR/tu.o"
+}]
+
+// RUN: sed -e "s|DIR|%/t|g" -e "s|INPUTS|%/S/Inputs|g" %t/cdb.json.template > 
%t/cdb.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full > %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
+
+// CHECK:  {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/first/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/first/module.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "first"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/first/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK:   

[PATCH] D137198: [clang][modules][deps] Parent module maps are affecting

2022-12-01 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf99e5a9106f0: [clang][modules][deps] Parent module maps are 
affecting (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137198

Files:
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/ClangScanDeps/modules-extern-submodule.c

Index: clang/test/ClangScanDeps/modules-extern-submodule.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/modules-extern-submodule.c
@@ -0,0 +1,128 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+//--- tu.m
+@import first;
+
+//--- first/first/module.modulemap
+module first { header "first.h" }
+//--- first/first/first.h
+#include 
+
+//--- second/second/module.modulemap
+module second { extern module sub "sub.modulemap" }
+//--- second/second/sub.modulemap
+module second.sub { header "sub.h" }
+//--- second/second/sub.h
+@import third;
+
+//--- third/module.modulemap
+module third {}
+
+//--- cdb.json.template
+[{
+  "file": "DIR/tu.c",
+  "directory": "DIR",
+  "command": "clang -I DIR/first -I DIR/second -I DIR/third -fmodules -fmodules-cache-path=DIR/cache -c DIR/tu.m -o DIR/tu.o"
+}]
+
+// RUN: sed "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full > %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
+
+// CHECK:   {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "module-name": "second"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "clang-modulemap-file": "[[PREFIX]]/first/first/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-cc1",
+// CHECK:  "-fmodule-map-file=[[PREFIX]]/second/second/module.modulemap"
+// CHECK-NOT:  "-fmodule-map-file=[[PREFIX]]/second/second/sub.modulemap"
+// CHECK-NOT:  "-fmodule-map-file=[[PREFIX]]/third/module.modulemap"
+// CHECK:  "-fmodule-file=second=[[PREFIX]]/cache/{{.*}}/second-{{.*}}.pcm"
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/first/first/first.h",
+// CHECK-NEXT: "[[PREFIX]]/first/first/module.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/second/second/module.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/second/second/sub.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "first"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "module-name": "third"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "clang-modulemap-file": "[[PREFIX]]/second/second/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-cc1",
+// CHECK:  "-fmodule-map-file=[[PREFIX]]/third/module.modulemap",
+// CHECK:  "-fmodule-file=third=[[PREFIX]]/cache/{{.*}}/third-{{.*}}.pcm",
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/second/second/module.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/second/second/sub.h",
+// CHECK-NEXT: "[[PREFIX]]/second/second/sub.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/third/module.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "second"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file": "[[PREFIX]]/third/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-cc1",
+// CHECK-NOT:  "-fmodule-map-file=
+// CHECK-NOT:  "-fmodule-file=third=
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/third/module.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "third"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "translation-units": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "commands": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-context-hash": "{{.*}}",
+// CHECK-NEXT:   "clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "module-name": "first"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-cc1",
+// CHECK:  

[PATCH] D137197: [clang][modules][deps] Transitive module maps are not affecting

2022-12-01 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGed07fe71d7bb: [clang][modules][deps] Transitive module maps 
are not affecting (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137197

Files:
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/ClangScanDeps/modules-transitive.c

Index: clang/test/ClangScanDeps/modules-transitive.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/modules-transitive.c
@@ -0,0 +1,58 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+//--- tu.m
+#include "first.h"
+
+//--- first/module.modulemap
+module first { header "first.h" }
+//--- first/first.h
+#include "second.h"
+
+//--- second/module.modulemap
+module second { header "second.h" }
+//--- second/second.h
+#include "third.h"
+
+//--- third/module.modulemap
+module third { header "third.h" }
+//--- third/third.h
+// empty
+
+//--- cdb.json.template
+[{
+  "file": "DIR/tu.c",
+  "directory": "DIR",
+  "command": "clang -I DIR/first -I DIR/second -I DIR/third -fmodules -fmodules-cache-path=DIR/cache -c DIR/tu.m -o DIR/tu.o"
+}]
+
+// RUN: sed "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full > %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
+
+// CHECK:  {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "module-name": "second"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "clang-modulemap-file": "[[PREFIX]]/first/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-cc1",
+// CHECK-NOT:  "-fmodule-map-file=[[PREFIX]]/third/module.modulemap"
+// CHECK:  "-fmodule-map-file=[[PREFIX]]/second/module.modulemap"
+// CHECK-NOT:  "-fmodule-map-file=[[PREFIX]]/third/module.modulemap"
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/first/first.h"
+// CHECK-NEXT: "[[PREFIX]]/first/module.modulemap"
+// CHECK-NEXT: "[[PREFIX]]/second/module.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "first"
+// CHECK-NEXT: }
+// CHECK:]
+// CHECK:  }
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -190,30 +190,20 @@
 }
   }
 
-  while (!ModulesToProcess.empty()) {
-auto *CurrentModule = ModulesToProcess.pop_back_val();
-ProcessedModules.insert(CurrentModule);
+  const ModuleMap  = HS.getModuleMap();
 
-Optional ModuleMapFile =
-HS.getModuleMap().getModuleMapFileForUniquing(CurrentModule);
-if (!ModuleMapFile) {
-  continue;
-}
-
-ModuleMaps.insert(*ModuleMapFile);
-
-for (auto *ImportedModule : (CurrentModule)->Imports) {
-  if (!ImportedModule ||
-  ProcessedModules.find(ImportedModule) != ProcessedModules.end()) {
-continue;
-  }
-  ModulesToProcess.push_back(ImportedModule);
-}
+  auto ProcessModuleOnce = [&](const Module *Mod) {
+if (ProcessedModules.insert(Mod).second)
+  if (auto ModuleMapFile = MM.getModuleMapFileForUniquing(Mod))
+ModuleMaps.insert(*ModuleMapFile);
+  };
 
+  for (const Module *CurrentModule : ModulesToProcess) {
+ProcessModuleOnce(CurrentModule);
+for (const Module *ImportedModule : CurrentModule->Imports)
+  ProcessModuleOnce(ImportedModule);
 for (const Module *UndeclaredModule : CurrentModule->UndeclaredUses)
-  if (UndeclaredModule &&
-  ProcessedModules.find(UndeclaredModule) == ProcessedModules.end())
-ModulesToProcess.push_back(UndeclaredModule);
+  ProcessModuleOnce(UndeclaredModule);
   }
 
   return ModuleMaps;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f99e5a9 - [clang][modules][deps] Parent module maps are affecting

2022-12-01 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-12-01T20:16:17-08:00
New Revision: f99e5a9106f08ad92a22c3b114d2052e5c502924

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

LOG: [clang][modules][deps] Parent module maps are affecting

Currently, the algorithm for gathering affecting module maps includes only 
those defining modules that include some headers. This is not entirely correct, 
though. Some module maps might be "importing" module maps for `extern` 
submodules. Such parent module maps are affecting - they do change semantics of 
the compilation. This patch adds parent module maps into the set of affecting 
module maps.

Depends on D137197.

Reviewed By: Bigcheese

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

Added: 
clang/test/ClangScanDeps/modules-extern-submodule.c

Modified: 
clang/lib/Serialization/ASTWriter.cpp

Removed: 




diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 80930357a6d1..1f5de568b3ba 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -192,10 +192,11 @@ std::set GetAffectingModuleMaps(const 
HeaderSearch ,
 
   const ModuleMap  = HS.getModuleMap();
 
-  auto ProcessModuleOnce = [&](const Module *Mod) {
-if (ProcessedModules.insert(Mod).second)
-  if (auto ModuleMapFile = MM.getModuleMapFileForUniquing(Mod))
-ModuleMaps.insert(*ModuleMapFile);
+  auto ProcessModuleOnce = [&](const Module *M) {
+for (const Module *Mod = M; Mod; Mod = Mod->Parent)
+  if (ProcessedModules.insert(Mod).second)
+if (auto ModuleMapFile = MM.getModuleMapFileForUniquing(Mod))
+  ModuleMaps.insert(*ModuleMapFile);
   };
 
   for (const Module *CurrentModule : ModulesToProcess) {

diff  --git a/clang/test/ClangScanDeps/modules-extern-submodule.c 
b/clang/test/ClangScanDeps/modules-extern-submodule.c
new file mode 100644
index ..bf1d41c1c2b0
--- /dev/null
+++ b/clang/test/ClangScanDeps/modules-extern-submodule.c
@@ -0,0 +1,128 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+//--- tu.m
+@import first;
+
+//--- first/first/module.modulemap
+module first { header "first.h" }
+//--- first/first/first.h
+#include 
+
+//--- second/second/module.modulemap
+module second { extern module sub "sub.modulemap" }
+//--- second/second/sub.modulemap
+module second.sub { header "sub.h" }
+//--- second/second/sub.h
+@import third;
+
+//--- third/module.modulemap
+module third {}
+
+//--- cdb.json.template
+[{
+  "file": "DIR/tu.c",
+  "directory": "DIR",
+  "command": "clang -I DIR/first -I DIR/second -I DIR/third -fmodules 
-fmodules-cache-path=DIR/cache -c DIR/tu.m -o DIR/tu.o"
+}]
+
+// RUN: sed "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full > %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
+
+// CHECK:   {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "module-name": "second"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/first/first/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-cc1",
+// CHECK:  
"-fmodule-map-file=[[PREFIX]]/second/second/module.modulemap"
+// CHECK-NOT:  
"-fmodule-map-file=[[PREFIX]]/second/second/sub.modulemap"
+// CHECK-NOT:  "-fmodule-map-file=[[PREFIX]]/third/module.modulemap"
+// CHECK:  
"-fmodule-file=second=[[PREFIX]]/cache/{{.*}}/second-{{.*}}.pcm"
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/first/first/first.h",
+// CHECK-NEXT: "[[PREFIX]]/first/first/module.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/second/second/module.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/second/second/sub.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "first"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "module-name": "third"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/second/second/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-cc1",
+// CHECK:  "-fmodule-map-file=[[PREFIX]]/third/module.modulemap",
+// CHECK:  
"-fmodule-file=third=[[PREFIX]]/cache/{{.*}}/third-{{.*}}.pcm",
+// CHECK:],
+// 

[clang] ed07fe7 - [clang][modules][deps] Transitive module maps are not affecting

2022-12-01 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-12-01T20:16:17-08:00
New Revision: ed07fe71d7bbdd13b113a2073f47e701e41a1001

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

LOG: [clang][modules][deps] Transitive module maps are not affecting

Currently, the algorithm for gathering affecting module maps includes those 
defining transitive dependencies. This seems like an over-approximation, since 
those don't change the semantics of current module build.

(With this patch, `ModulesToProcess` only ever holds modules whose headers will 
be serialized into the current PCM.)

Reviewed By: Bigcheese

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

Added: 
clang/test/ClangScanDeps/modules-transitive.c

Modified: 
clang/lib/Serialization/ASTWriter.cpp

Removed: 




diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index f1dab7e051e2..80930357a6d1 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -190,30 +190,20 @@ std::set GetAffectingModuleMaps(const 
HeaderSearch ,
 }
   }
 
-  while (!ModulesToProcess.empty()) {
-auto *CurrentModule = ModulesToProcess.pop_back_val();
-ProcessedModules.insert(CurrentModule);
+  const ModuleMap  = HS.getModuleMap();
 
-Optional ModuleMapFile =
-HS.getModuleMap().getModuleMapFileForUniquing(CurrentModule);
-if (!ModuleMapFile) {
-  continue;
-}
-
-ModuleMaps.insert(*ModuleMapFile);
-
-for (auto *ImportedModule : (CurrentModule)->Imports) {
-  if (!ImportedModule ||
-  ProcessedModules.find(ImportedModule) != ProcessedModules.end()) {
-continue;
-  }
-  ModulesToProcess.push_back(ImportedModule);
-}
+  auto ProcessModuleOnce = [&](const Module *Mod) {
+if (ProcessedModules.insert(Mod).second)
+  if (auto ModuleMapFile = MM.getModuleMapFileForUniquing(Mod))
+ModuleMaps.insert(*ModuleMapFile);
+  };
 
+  for (const Module *CurrentModule : ModulesToProcess) {
+ProcessModuleOnce(CurrentModule);
+for (const Module *ImportedModule : CurrentModule->Imports)
+  ProcessModuleOnce(ImportedModule);
 for (const Module *UndeclaredModule : CurrentModule->UndeclaredUses)
-  if (UndeclaredModule &&
-  ProcessedModules.find(UndeclaredModule) == ProcessedModules.end())
-ModulesToProcess.push_back(UndeclaredModule);
+  ProcessModuleOnce(UndeclaredModule);
   }
 
   return ModuleMaps;

diff  --git a/clang/test/ClangScanDeps/modules-transitive.c 
b/clang/test/ClangScanDeps/modules-transitive.c
new file mode 100644
index ..9ae1554d9811
--- /dev/null
+++ b/clang/test/ClangScanDeps/modules-transitive.c
@@ -0,0 +1,58 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+//--- tu.m
+#include "first.h"
+
+//--- first/module.modulemap
+module first { header "first.h" }
+//--- first/first.h
+#include "second.h"
+
+//--- second/module.modulemap
+module second { header "second.h" }
+//--- second/second.h
+#include "third.h"
+
+//--- third/module.modulemap
+module third { header "third.h" }
+//--- third/third.h
+// empty
+
+//--- cdb.json.template
+[{
+  "file": "DIR/tu.c",
+  "directory": "DIR",
+  "command": "clang -I DIR/first -I DIR/second -I DIR/third -fmodules 
-fmodules-cache-path=DIR/cache -c DIR/tu.m -o DIR/tu.o"
+}]
+
+// RUN: sed "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full > %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
+
+// CHECK:  {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "module-name": "second"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/first/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-cc1",
+// CHECK-NOT:  "-fmodule-map-file=[[PREFIX]]/third/module.modulemap"
+// CHECK:  "-fmodule-map-file=[[PREFIX]]/second/module.modulemap"
+// CHECK-NOT:  "-fmodule-map-file=[[PREFIX]]/third/module.modulemap"
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/first/first.h"
+// CHECK-NEXT: "[[PREFIX]]/first/module.modulemap"
+// CHECK-NEXT: "[[PREFIX]]/second/module.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "first"
+// CHECK-NEXT: }
+// CHECK:]
+// CHECK:  }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D139167: [clang][Windows]Ignore Options '/d1nodatetime' and '/d1import_no_registry'

2022-12-01 Thread Qfrost via Phabricator via cfe-commits
Qfrost911 created this revision.
Qfrost911 added reviewers: aaron.ballman, pengfei, JosephTremoulet, efriedma.
Herald added a project: All.
Qfrost911 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Using clang and VS to build Windows Kernel Driver, two errors will be raised

  1>clang-cl : error : no such file or directory: '/d1nodatetime'
  1>clang-cl : error : no such file or directory: '/d1import_no_registry'

In the patch, I ignore these options in order to build windows driver under 
visual studio.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D139167

Files:
  clang/include/clang/Driver/Options.td


Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -6914,7 +6914,10 @@
 def _SLASH_Zm : CLIgnoredJoined<"Zm">;
 def _SLASH_Zo : CLIgnoredFlag<"Zo">;
 def _SLASH_Zo_ : CLIgnoredFlag<"Zo-">;
-
+def _SLASH_d1nodatetime : CLIgnoredFlag<"d1nodatetime">,
+  HelpText<"d1nodatetime">;
+def _SLASH_d1import_no_registry : CLIgnoredFlag<"d1import_no_registry">,
+  HelpText<"d1import_no_registry">;
 
 // Unsupported:
 


Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -6914,7 +6914,10 @@
 def _SLASH_Zm : CLIgnoredJoined<"Zm">;
 def _SLASH_Zo : CLIgnoredFlag<"Zo">;
 def _SLASH_Zo_ : CLIgnoredFlag<"Zo-">;
-
+def _SLASH_d1nodatetime : CLIgnoredFlag<"d1nodatetime">,
+  HelpText<"d1nodatetime">;
+def _SLASH_d1import_no_registry : CLIgnoredFlag<"d1import_no_registry">,
+  HelpText<"d1import_no_registry">;
 
 // Unsupported:
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137192: [clang][serialization] NFCI: Avoid re-reading input file info

2022-12-01 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG66cf61abd849: [clang][serialization] NFCI: Avoid re-reading 
input file info (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D137192?vs=472393=479513#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137192

Files:
  clang/include/clang/Serialization/ASTReader.h
  clang/include/clang/Serialization/ModuleFile.h
  clang/lib/Serialization/ASTReader.cpp

Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -2266,8 +2266,15 @@
   return false;
 }
 
-ASTReader::InputFileInfo
-ASTReader::readInputFileInfo(ModuleFile , unsigned ID) {
+InputFileInfo ASTReader::getInputFileInfo(ModuleFile , unsigned ID) {
+  // If this ID is bogus, just return an empty input file.
+  if (ID == 0 || ID > F.InputFileInfosLoaded.size())
+return InputFileInfo();
+
+  // If we've already loaded this input file, return it.
+  if (!F.InputFileInfosLoaded[ID - 1].Filename.empty())
+return F.InputFileInfosLoaded[ID - 1];
+
   // Go find this input file.
   BitstreamCursor  = F.InputFilesCursor;
   SavedStreamPosition SavedPosition(Cursor);
@@ -2320,6 +2327,9 @@
   }
   R.ContentHash = (static_cast(Record[1]) << 32) |
   static_cast(Record[0]);
+
+  // Note that we've loaded this input file info.
+  F.InputFileInfosLoaded[ID - 1] = R;
   return R;
 }
 
@@ -2344,7 +2354,7 @@
 consumeError(std::move(Err));
   }
 
-  InputFileInfo FI = readInputFileInfo(F, ID);
+  InputFileInfo FI = getInputFileInfo(F, ID);
   off_t StoredSize = FI.StoredSize;
   time_t StoredTime = FI.StoredTime;
   bool Overridden = FI.Overridden;
@@ -2691,7 +2701,7 @@
 : NumUserInputs;
 for (unsigned I = 0; I < N; ++I) {
   bool IsSystem = I >= NumUserInputs;
-  InputFileInfo FI = readInputFileInfo(F, I+1);
+  InputFileInfo FI = getInputFileInfo(F, I + 1);
   Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
F.Kind == MK_ExplicitModule ||
F.Kind == MK_PrebuiltModule);
@@ -2968,6 +2978,7 @@
   F.InputFileOffsets =
   (const llvm::support::unaligned_uint64_t *)Blob.data();
   F.InputFilesLoaded.resize(NumInputs);
+  F.InputFileInfosLoaded.resize(NumInputs);
   F.NumUserInputFiles = NumUserInputs;
   break;
 }
@@ -2983,7 +2994,7 @@
 
   for (unsigned I = 0; I < FileCount; ++I) {
 size_t ID = endian::readNext(D);
-InputFileInfo IFI = readInputFileInfo(F, ID);
+InputFileInfo IFI = getInputFileInfo(F, ID);
 if (llvm::ErrorOr File =
 PP.getFileManager().getFile(IFI.Filename))
   PP.getIncludedFiles().insert(*File);
@@ -9217,9 +9228,8 @@
 llvm::function_ref Visitor) {
   unsigned NumInputs = MF.InputFilesLoaded.size();
   for (unsigned I = 0; I < NumInputs; ++I) {
-InputFileInfo IFI = readInputFileInfo(MF, I + 1);
+InputFileInfo IFI = getInputFileInfo(MF, I + 1);
 if (IFI.TopLevelModuleMap)
-  // FIXME: This unnecessarily re-reads the InputFileInfo.
   if (auto FE = getInputFile(MF, I + 1).getFile())
 Visitor(*FE);
   }
Index: clang/include/clang/Serialization/ModuleFile.h
===
--- clang/include/clang/Serialization/ModuleFile.h
+++ clang/include/clang/Serialization/ModuleFile.h
@@ -59,6 +59,17 @@
   MK_PrebuiltModule
 };
 
+/// The input file info that has been loaded from an AST file.
+struct InputFileInfo {
+  std::string Filename;
+  uint64_t ContentHash;
+  off_t StoredSize;
+  time_t StoredTime;
+  bool Overridden;
+  bool Transient;
+  bool TopLevelModuleMap;
+};
+
 /// The input file that has been loaded from this AST file, along with
 /// bools indicating whether this was an overridden buffer or if it was
 /// out-of-date or not-found.
@@ -235,6 +246,9 @@
   /// The input files that have been loaded from this AST file.
   std::vector InputFilesLoaded;
 
+  /// The input file infos that have been loaded from this AST file.
+  std::vector InputFileInfosLoaded;
+
   // All user input files reside at the index range [0, NumUserInputFiles), and
   // system input files reside at [NumUserInputFiles, InputFilesLoaded.size()).
   unsigned NumUserInputFiles = 0;
Index: clang/include/clang/Serialization/ASTReader.h
===
--- clang/include/clang/Serialization/ASTReader.h
+++ clang/include/clang/Serialization/ASTReader.h
@@ -1247,18 +1247,8 @@
   /// Reads a statement from the specified cursor.
   Stmt *ReadStmtFromStream(ModuleFile );
 
-  struct InputFileInfo {
-std::string Filename;
-uint64_t 

[clang] 66cf61a - [clang][serialization] NFCI: Avoid re-reading input file info

2022-12-01 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-12-01T20:07:01-08:00
New Revision: 66cf61abd849072d04da96408b122eea436dbc90

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

LOG: [clang][serialization] NFCI: Avoid re-reading input file info

This patch resolves a FIXME that points out an inefficiency in first 
deserializing the input file info and the whole input file, which redundantly 
deserializes the input file info again.

Reviewed By: Bigcheese

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

Added: 


Modified: 
clang/include/clang/Serialization/ASTReader.h
clang/include/clang/Serialization/ModuleFile.h
clang/lib/Serialization/ASTReader.cpp

Removed: 




diff  --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index 5569c0147bbd6..21cbe4f5b1a50 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -1247,18 +1247,8 @@ class ASTReader
   /// Reads a statement from the specified cursor.
   Stmt *ReadStmtFromStream(ModuleFile );
 
-  struct InputFileInfo {
-std::string Filename;
-uint64_t ContentHash;
-off_t StoredSize;
-time_t StoredTime;
-bool Overridden;
-bool Transient;
-bool TopLevelModuleMap;
-  };
-
-  /// Reads the stored information about an input file.
-  InputFileInfo readInputFileInfo(ModuleFile , unsigned ID);
+  /// Retrieve the stored information about an input file.
+  serialization::InputFileInfo getInputFileInfo(ModuleFile , unsigned ID);
 
   /// Retrieve the file entry and 'overridden' bit for an input
   /// file in the given module file.

diff  --git a/clang/include/clang/Serialization/ModuleFile.h 
b/clang/include/clang/Serialization/ModuleFile.h
index 500dab59ed5e0..655ae022a488a 100644
--- a/clang/include/clang/Serialization/ModuleFile.h
+++ b/clang/include/clang/Serialization/ModuleFile.h
@@ -59,6 +59,17 @@ enum ModuleKind {
   MK_PrebuiltModule
 };
 
+/// The input file info that has been loaded from an AST file.
+struct InputFileInfo {
+  std::string Filename;
+  uint64_t ContentHash;
+  off_t StoredSize;
+  time_t StoredTime;
+  bool Overridden;
+  bool Transient;
+  bool TopLevelModuleMap;
+};
+
 /// The input file that has been loaded from this AST file, along with
 /// bools indicating whether this was an overridden buffer or if it was
 /// out-of-date or not-found.
@@ -235,6 +246,9 @@ class ModuleFile {
   /// The input files that have been loaded from this AST file.
   std::vector InputFilesLoaded;
 
+  /// The input file infos that have been loaded from this AST file.
+  std::vector InputFileInfosLoaded;
+
   // All user input files reside at the index range [0, NumUserInputFiles), and
   // system input files reside at [NumUserInputFiles, InputFilesLoaded.size()).
   unsigned NumUserInputFiles = 0;

diff  --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index ff324cab57bf7..97fdfbe332ad5 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -2266,8 +2266,15 @@ bool ASTReader::shouldDisableValidationForFile(
   return false;
 }
 
-ASTReader::InputFileInfo
-ASTReader::readInputFileInfo(ModuleFile , unsigned ID) {
+InputFileInfo ASTReader::getInputFileInfo(ModuleFile , unsigned ID) {
+  // If this ID is bogus, just return an empty input file.
+  if (ID == 0 || ID > F.InputFileInfosLoaded.size())
+return InputFileInfo();
+
+  // If we've already loaded this input file, return it.
+  if (!F.InputFileInfosLoaded[ID - 1].Filename.empty())
+return F.InputFileInfosLoaded[ID - 1];
+
   // Go find this input file.
   BitstreamCursor  = F.InputFilesCursor;
   SavedStreamPosition SavedPosition(Cursor);
@@ -2320,6 +2327,9 @@ ASTReader::readInputFileInfo(ModuleFile , unsigned ID) {
   }
   R.ContentHash = (static_cast(Record[1]) << 32) |
   static_cast(Record[0]);
+
+  // Note that we've loaded this input file info.
+  F.InputFileInfosLoaded[ID - 1] = R;
   return R;
 }
 
@@ -2344,7 +2354,7 @@ InputFile ASTReader::getInputFile(ModuleFile , unsigned 
ID, bool Complain) {
 consumeError(std::move(Err));
   }
 
-  InputFileInfo FI = readInputFileInfo(F, ID);
+  InputFileInfo FI = getInputFileInfo(F, ID);
   off_t StoredSize = FI.StoredSize;
   time_t StoredTime = FI.StoredTime;
   bool Overridden = FI.Overridden;
@@ -2691,7 +2701,7 @@ ASTReader::ReadControlBlock(ModuleFile ,
 : 
NumUserInputs;
 for (unsigned I = 0; I < N; ++I) {
   bool IsSystem = I >= NumUserInputs;
-  InputFileInfo FI = readInputFileInfo(F, I+1);
+  InputFileInfo FI = getInputFileInfo(F, I + 1);
   Listener->visitInputFile(FI.Filename, 

[PATCH] D139166: [OPENMP51] Codegen support for error directive.

2022-12-01 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.h:334
   llvm::Value *emitUpdateLocation(CodeGenFunction , SourceLocation Loc,
-  unsigned Flags = 0);
+  unsigned Flags = 0, bool EmitLoc = false);
 

Why the new argument?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139166

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


[clang] 935a07e - [clang][deps][lex] Avoid canonicalization of remapped framework directories

2022-12-01 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-12-01T19:59:54-08:00
New Revision: 935a07ed21434825a96eb6d3acd2163edd0abe88

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

LOG: [clang][deps][lex] Avoid canonicalization of remapped framework directories

In D134923, the scanner introduced canonicalization of framework directories 
when reporting module map paths in order to increase module sharing. However, 
if we canonicalize framework directory that plays a role in a VFS remapping, 
and later try to use that module map to build the module, header lookup can 
fail. This happens when the module headers are remapped using the original 
framework path.

This patch fixes that. The implementation relies on the fact that the chain of 
directories in VFS remapping are assigned `DirectoryEntry` objects distinct 
from their on-disk counterparts. If we detect that case, we avoid the 
canonicalization.

Reviewed By: benlangmuir

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

Added: 
clang/test/ClangScanDeps/modules-symlink-dir-vfs.c

Modified: 
clang/lib/Lex/ModuleMap.cpp

Removed: 




diff  --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp
index 9ff0204941c02..4e86c5c694441 100644
--- a/clang/lib/Lex/ModuleMap.cpp
+++ b/clang/lib/Lex/ModuleMap.cpp
@@ -1303,9 +1303,16 @@ 
ModuleMap::canonicalizeModuleMapPath(SmallVectorImpl ) {
   // Canonicalize the directory.
   StringRef CanonicalDir = FM.getCanonicalName(*DirEntry);
   if (CanonicalDir != Dir) {
-bool Done = llvm::sys::path::replace_path_prefix(Path, Dir, CanonicalDir);
-(void)Done;
-assert(Done && "Path should always start with Dir");
+auto CanonicalDirEntry = FM.getDirectory(CanonicalDir);
+// Only use the canonicalized path if it resolves to the same entry as the
+// original. This is not true if there's a VFS overlay on top of a FS where
+// the directory is a symlink. The overlay would not remap the target path
+// of the symlink to the same directory entry in that case.
+if (CanonicalDirEntry && *CanonicalDirEntry == *DirEntry) {
+  bool Done = llvm::sys::path::replace_path_prefix(Path, Dir, 
CanonicalDir);
+  (void)Done;
+  assert(Done && "Path should always start with Dir");
+}
   }
 
   // In theory, the filename component should also be canonicalized if it

diff  --git a/clang/test/ClangScanDeps/modules-symlink-dir-vfs.c 
b/clang/test/ClangScanDeps/modules-symlink-dir-vfs.c
new file mode 100644
index 0..bc384b015e6f9
--- /dev/null
+++ b/clang/test/ClangScanDeps/modules-symlink-dir-vfs.c
@@ -0,0 +1,90 @@
+// This test checks that we're not canonicalizing framework directories that
+// play a role in VFS remapping. This could lead header search to fail when
+// building that module.
+
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// REQUIRES: shell
+
+// RUN: mkdir -p %t/frameworks-symlink
+// RUN: ln -s %t/frameworks/FW.framework %t/frameworks-symlink/FW.framework
+
+// RUN: mkdir -p %t/copy
+// RUN: cp %t/frameworks/FW.framework/Headers/FW.h %t/copy
+// RUN: cp %t/frameworks/FW.framework/Headers/Header.h %t/copy
+
+//--- frameworks/FW.framework/Modules/module.modulemap
+framework module FW { umbrella header "FW.h" }
+//--- frameworks/FW.framework/Headers/FW.h
+#import 
+//--- frameworks/FW.framework/Headers/Header.h
+// empty
+
+//--- tu.m
+@import FW;
+
+//--- overlay.json.template
+{
+  "version": 0,
+  "case-sensitive": "false",
+  "roots": [
+{
+  "contents": [
+{
+  "external-contents": "DIR/copy/Header.h",
+  "name": "Header.h",
+  "type": "file"
+},
+{
+  "external-contents": "DIR/copy/FW.h",
+  "name": "FW.h",
+  "type": "file"
+}
+  ],
+  "name": "DIR/frameworks-symlink/FW.framework/Headers",
+  "type": "directory"
+}
+  ]
+}
+
+//--- cdb.json.template
+[{
+  "directory": "DIR",
+  "file": "DIR/tu.m",
+  "command": "clang -fmodules -fmodules-cache-path=DIR/cache -ivfsoverlay 
DIR/overlay.json -F DIR/frameworks-symlink -c DIR/tu.m -o DIR/tu.o 
-Werror=non-modular-include-in-framework-module"
+}]
+
+// RUN: sed -e "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+// RUN: sed -e "s|DIR|%/t|g" %t/overlay.json.template > %t/overlay.json
+
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full > %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
+
+// CHECK:  {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/frameworks-symlink/FW.framework/Modules/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-cc1",
+// CHECK: 

[PATCH] D135841: [clang][deps][lex] Avoid canonicalization of remapped framework directories

2022-12-01 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG935a07ed2143: [clang][deps][lex] Avoid canonicalization of 
remapped framework directories (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D135841?vs=467339=479512#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135841

Files:
  clang/lib/Lex/ModuleMap.cpp
  clang/test/ClangScanDeps/modules-symlink-dir-vfs.c

Index: clang/test/ClangScanDeps/modules-symlink-dir-vfs.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/modules-symlink-dir-vfs.c
@@ -0,0 +1,90 @@
+// This test checks that we're not canonicalizing framework directories that
+// play a role in VFS remapping. This could lead header search to fail when
+// building that module.
+
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// REQUIRES: shell
+
+// RUN: mkdir -p %t/frameworks-symlink
+// RUN: ln -s %t/frameworks/FW.framework %t/frameworks-symlink/FW.framework
+
+// RUN: mkdir -p %t/copy
+// RUN: cp %t/frameworks/FW.framework/Headers/FW.h %t/copy
+// RUN: cp %t/frameworks/FW.framework/Headers/Header.h %t/copy
+
+//--- frameworks/FW.framework/Modules/module.modulemap
+framework module FW { umbrella header "FW.h" }
+//--- frameworks/FW.framework/Headers/FW.h
+#import 
+//--- frameworks/FW.framework/Headers/Header.h
+// empty
+
+//--- tu.m
+@import FW;
+
+//--- overlay.json.template
+{
+  "version": 0,
+  "case-sensitive": "false",
+  "roots": [
+{
+  "contents": [
+{
+  "external-contents": "DIR/copy/Header.h",
+  "name": "Header.h",
+  "type": "file"
+},
+{
+  "external-contents": "DIR/copy/FW.h",
+  "name": "FW.h",
+  "type": "file"
+}
+  ],
+  "name": "DIR/frameworks-symlink/FW.framework/Headers",
+  "type": "directory"
+}
+  ]
+}
+
+//--- cdb.json.template
+[{
+  "directory": "DIR",
+  "file": "DIR/tu.m",
+  "command": "clang -fmodules -fmodules-cache-path=DIR/cache -ivfsoverlay DIR/overlay.json -F DIR/frameworks-symlink -c DIR/tu.m -o DIR/tu.o -Werror=non-modular-include-in-framework-module"
+}]
+
+// RUN: sed -e "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+// RUN: sed -e "s|DIR|%/t|g" %t/overlay.json.template > %t/overlay.json
+
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full > %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
+
+// CHECK:  {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file": "[[PREFIX]]/frameworks-symlink/FW.framework/Modules/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-cc1",
+// CHECK:  "-emit-module",
+// CHECK-NEXT: "-x",
+// CHECK-NEXT: "objective-c",
+// CHECK-NEXT: "[[PREFIX]]/frameworks-symlink/FW.framework/Modules/module.modulemap",
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/copy/FW.h",
+// CHECK-NEXT: "[[PREFIX]]/copy/Header.h",
+// CHECK-NEXT: "[[PREFIX]]/frameworks-symlink/FW.framework/Modules/module.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "FW"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "translation-units": [
+// CHECK:]
+// CHECK:  }
+
+// RUN: %deps-to-rsp %t/result.json --module-name=FW > %t/FW.cc1.rsp
+// RUN: %clang @%t/FW.cc1.rsp
Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -1303,9 +1303,16 @@
   // Canonicalize the directory.
   StringRef CanonicalDir = FM.getCanonicalName(*DirEntry);
   if (CanonicalDir != Dir) {
-bool Done = llvm::sys::path::replace_path_prefix(Path, Dir, CanonicalDir);
-(void)Done;
-assert(Done && "Path should always start with Dir");
+auto CanonicalDirEntry = FM.getDirectory(CanonicalDir);
+// Only use the canonicalized path if it resolves to the same entry as the
+// original. This is not true if there's a VFS overlay on top of a FS where
+// the directory is a symlink. The overlay would not remap the target path
+// of the symlink to the same directory entry in that case.
+if (CanonicalDirEntry && *CanonicalDirEntry == *DirEntry) {
+  bool Done = llvm::sys::path::replace_path_prefix(Path, Dir, CanonicalDir);
+  (void)Done;
+  assert(Done && "Path should always start with Dir");
+}
   }
 
   // In theory, the filename component should also be canonicalized if it
___
cfe-commits mailing list

[PATCH] D137706: [clang][Interp] Implement IntegralToPointer casts

2022-12-01 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added a comment.

I agree with @aaron.ballman I expect some more tests for this.




Comment at: clang/lib/AST/Interp/Pointer.h:70
   Pointer(Block *B, unsigned BaseAndOffset);
+  Pointer(unsigned Offset);
   Pointer(const Pointer );

Is the only cast we have a `Pointer` that is a `nullptr` but has an `Offset` is 
from a integral to pointer cast? 


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

https://reviews.llvm.org/D137706

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


[PATCH] D139166: [OPENMP51] Codegen support for error directive.

2022-12-01 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 created this revision.
jyu2 added reviewers: ABataev, jdoerfert, mikerice.
jyu2 added projects: OpenMP, clang.
Herald added subscribers: guansong, yaxunl.
Herald added a project: All.
jyu2 requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, sstefan1.
Herald added a project: LLVM.

Added codegen for `error` directive.
Generate IR to call: void __kmpc_error(ident_t *loc, int severity, const char 
*message);


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D139166

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/test/OpenMP/error_codegen.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPKinds.def

Index: llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
===
--- llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
+++ llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
@@ -198,6 +198,7 @@
 __OMP_RTL(__kmpc_barrier, false, Void, IdentPtr, Int32)
 __OMP_RTL(__kmpc_cancel, false, Int32, IdentPtr, Int32, Int32)
 __OMP_RTL(__kmpc_cancel_barrier, false, Int32, IdentPtr, Int32)
+__OMP_RTL(__kmpc_error, false, Void, IdentPtr, Int32, Int8Ptr)
 __OMP_RTL(__kmpc_flush, false, Void, IdentPtr)
 __OMP_RTL(__kmpc_global_thread_num, false, Int32, IdentPtr)
 __OMP_RTL(__kmpc_get_hardware_thread_id_in_block, false, Int32, )
Index: clang/test/OpenMP/error_codegen.cpp
===
--- /dev/null
+++ clang/test/OpenMP/error_codegen.cpp
@@ -0,0 +1,67 @@
+// RUN: %clang_cc1 -std=c++11 -fopenmp -fopenmp-version=51 -triple x86_64 \
+// RUN:   -emit-llvm -o - %s | FileCheck %s
+
+// RUN: %clang_cc1 -std=c++11 -fopenmp-simd -fopenmp-version=51 \
+// RUN:  -debug-info-kind=limited -triple x86_64 -emit-llvm -o - %s |  \
+// RUN:  FileCheck  --check-prefix SIMD %s
+
+//CHECK: @.str = private unnamed_addr constant [23 x i8] c"GPU compiler required.\00", align 1
+//CHECK: @0 = private unnamed_addr constant {{.*}}error_codegen.cpp;main;52;1;;\00", align 1
+//CHECK: @1 = private unnamed_addr constant %struct.ident_t { i32 0, i32 2, i32 0, i32 {{.*}}, ptr @0 }, align 8
+//CHECK: @.str.1 = private unnamed_addr constant [27 x i8] c"Note this is functioncall.\00", align 1
+//CHECK: @2 = private unnamed_addr constant {{.*}}error_codegen.cpp;main;54;1;;\00", align 1
+//CHECK: @3 = private unnamed_addr constant %struct.ident_t { i32 0, i32 2, i32 0, i32 {{.*}}, ptr @2 }, align 8
+//CHECK: @.str.2 = private unnamed_addr constant [23 x i8] c"GNU compiler required.\00", align 1
+//CHECK: @4 = private unnamed_addr constant {{.*}}error_codegen.cpp;tmain;29;1;;\00", align 1
+//CHECK: @5 = private unnamed_addr constant %struct.ident_t { i32 0, i32 2, i32 0, i32 {{.*}}, ptr @4 }, align 8
+//CHECK: @.str.3 = private unnamed_addr constant [22 x i8] c"Notice: add for loop.\00", align 1
+//CHECK: @6 = private unnamed_addr constant {{.*}}error_codegen.cpp;tmain;32;1;;\00", align 1
+//CHECK: @7 = private unnamed_addr constant %struct.ident_t { i32 0, i32 2, i32 0, i32 {{.*}}, ptr @6 }, align 8
+//CHECK: @8 = private unnamed_addr constant {{.*}}error_codegen.cpp;tmain;38;1;;\00", align 1
+//CHECK: @9 = private unnamed_addr constant %struct.ident_t { i32 0, i32 2, i32 0, i32 {{.*}}, ptr @8 }, align 8
+
+void foo() {}
+
+template 
+int tmain(T argc, char **argv) {
+  T b = argc, c, d, e, f, g;
+  static int a;
+#pragma omp error at(execution) severity(fatal) message("GNU compiler required.")
+  a = argv[0][0];
+  ++a;
+#pragma omp error at(execution) severity(warning) message("Notice: add for loop.")
+  {
+int b = 10;
+T c = 100;
+a = b + c;
+  }
+#pragma omp  error at(execution) severity(fatal) message("GPU compiler required.")
+  foo();
+return N;
+}
+// CHECK-LABEL: @main(
+// SIMD-LABEL: @main(
+// CHECK:call void @__kmpc_error(ptr @1, i32 2, ptr @.str)
+// SIMD-NOT:call void @__kmpc_error(ptr @1, i32 2, ptr @.str)
+// CHECK:call void @__kmpc_error(ptr @3, i32 1, ptr @.str.1)
+// SIMD-NOT:call void @__kmpc_error(ptr @3, i32 1, ptr @.str.1)
+//
+int main (int argc, char **argv) {
+  int b = argc, c, d, e, f, g;
+  static int a;
+#pragma omp error at(execution) severity(fatal) message("GPU compiler required.")
+   a=2;
+#pragma omp error at(execution) severity(warning) message("Note this is functioncall.")
+  foo();
+  tmain(argc, argv);
+}
+
+//CHECK-LABEL: @_Z5tmainIiLi10EEiT_PPc(
+//SIMD-LABEL: @_Z5tmainIiLi10EEiT_PPc(
+//CHECK: call void @__kmpc_error(ptr @5, i32 2, ptr @.str.2)
+//CHECK: call void @__kmpc_error(ptr @7, i32 1, ptr @.str.3)
+//CHECK: call void @__kmpc_error(ptr @9, i32 2, ptr @.str)
+//SIMD-NOT: call void @__kmpc_error(ptr @5, i32 2, ptr @.str.2)
+//SIMD-NOT: call void @__kmpc_error(ptr @7, i32 1, ptr @.str.3)
+//SIMD-NOT: call void @__kmpc_error(ptr @9, i32 2, ptr @.str)
+//CHECK: ret i32 10
Index: clang/lib/CodeGen/CGStmtOpenMP.cpp

[PATCH] D138597: DebugInfo: Add/support new DW_LANG codes for recent C and C++ versions

2022-12-01 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

Don't know that I've got it in me right now to do the more invasive change of 
updating the LLVM DebugInfo IR metadata to carry the DWARFv6 style 
language+version stuff (perhaps especially if that's going to go alongside the 
DWARFv5 and earlier pure language encoding)

I could do the minimum and fix the C version case to use the DWARFv5-shipped 
C11 encoding. And perhaps add the post-v5 backported language encodings to LLVM 
so at least llvm-dwarfdump can detect/render/handle them correctly for name 
printing, etc.

Or I could maybe do something in between - where the post-v5 backported 
language codes could be used in the IR and then LLVM could detect those and 
remap them to v5-shipped DW_AT_language + v6-not-ready-yet (using an extension 
form? Using the form that's not shipped in v6 yet?) attributes?

Seems like it's probably not worth emitting the v6 stuff until it's baked. And 
not worth emitting the post-v5 backported attributes due to risk of breakage? 
So maybe just do the minimum?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138597

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


[PATCH] D138597: DebugInfo: Add/support new DW_LANG codes for recent C and C++ versions

2022-12-01 Thread David Blaikie via Phabricator via cfe-commits
dblaikie updated this revision to Diff 479499.
dblaikie added a comment.

Add llvm testing (but I'm going to rework this a lot, so this is just a 
snapshot for history)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138597

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGen/debug-info-programming-language.c
  clang/test/CodeGenCXX/debug-info-programming-language.cpp
  llvm/include/llvm-c/DebugInfo.h
  llvm/include/llvm/BinaryFormat/Dwarf.def
  llvm/include/llvm/BinaryFormat/Dwarf.h
  llvm/lib/IR/DIBuilder.cpp
  llvm/test/DebugInfo/X86/assumed_size_array.ll
  llvm/test/DebugInfo/X86/dwarf-public-names.ll

Index: llvm/test/DebugInfo/X86/dwarf-public-names.ll
===
--- llvm/test/DebugInfo/X86/dwarf-public-names.ll
+++ llvm/test/DebugInfo/X86/dwarf-public-names.ll
@@ -4,6 +4,24 @@
 ; RUN: llvm-dwarfdump -debug-pubnames %t.o | FileCheck --check-prefix=NOPUB %s
 ; RUN: llc -mtriple=x86_64-scei-ps4 -filetype=obj -o %t.o < %s
 ; RUN: llvm-dwarfdump -debug-pubnames %t.o | FileCheck --check-prefix=NOPUB %s
+
+; RUN: rm -rf %t
+; RUN: mkdir %t
+; RUN: sed -e "s/C_plus_plus/C_plus_plus_03/" %s > %t/test.ll
+; RUN: llc -mtriple=x86_64-pc-linux-gnu -filetype=obj -o %t/test.o < %t/test.ll
+; RUN: llvm-dwarfdump -debug-pubnames %t/test.o | FileCheck --check-prefix=LINUX %s
+; RUN: sed -e "s/C_plus_plus/C_plus_plus_11/" %s > %t/test.ll
+; RUN: llc -mtriple=x86_64-pc-linux-gnu -filetype=obj -o %t/test.o < %t/test.ll
+; RUN: llvm-dwarfdump -debug-pubnames %t/test.o | FileCheck --check-prefix=LINUX %s
+; RUN: sed -e "s/C_plus_plus/C_plus_plus_14/" %s > %t/test.ll
+; RUN: llc -mtriple=x86_64-pc-linux-gnu -filetype=obj -o %t/test.o < %t/test.ll
+; RUN: llvm-dwarfdump -debug-pubnames %t/test.o | FileCheck --check-prefix=LINUX %s
+; RUN: sed -e "s/C_plus_plus/C_plus_plus_17/" %s > %t/test.ll
+; RUN: llc -mtriple=x86_64-pc-linux-gnu -filetype=obj -o %t/test.o < %t/test.ll
+; RUN: llvm-dwarfdump -debug-pubnames %t/test.o | FileCheck --check-prefix=LINUX %s
+; RUN: sed -e "s/C_plus_plus/C_plus_plus_20/" %s > %t/test.ll
+; RUN: llc -mtriple=x86_64-pc-linux-gnu -filetype=obj -o %t/test.o < %t/test.ll
+; RUN: llvm-dwarfdump -debug-pubnames %t/test.o | FileCheck --check-prefix=LINUX %s
 ; ModuleID = 'dwarf-public-names.cpp'
 ;
 ; Generated from:
Index: llvm/test/DebugInfo/X86/assumed_size_array.ll
===
--- llvm/test/DebugInfo/X86/assumed_size_array.ll
+++ llvm/test/DebugInfo/X86/assumed_size_array.ll
@@ -3,6 +3,11 @@
 
 ; RUN: llc -mtriple=x86_64-unknown-linux-gnu %s -filetype=obj -o %t.o
 ; RUN: llvm-dwarfdump  %t.o | FileCheck %s
+; RUN: rm -rf %t
+; RUN: mkdir %t
+; RUN: sed -e "s/Fortran90/Fortran18/" %s > %t/test.ll
+; RUN: llc -mtriple=x86_64-unknown-linux-gnu %t/test.ll -filetype=obj -o %t/test.o
+; RUN: llvm-dwarfdump  %t/test.o | FileCheck %s
 
 ; CHECK-LABEL: DW_TAG_formal_parameter
 ; CHECK: DW_AT_name("array1")
Index: llvm/lib/IR/DIBuilder.cpp
===
--- llvm/lib/IR/DIBuilder.cpp
+++ llvm/lib/IR/DIBuilder.cpp
@@ -156,7 +156,7 @@
 DICompileUnit::DebugNameTableKind NameTableKind, bool RangesBaseAddress,
 StringRef SysRoot, StringRef SDK) {
 
-  assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
+  assert(((Lang <= dwarf::DW_LANG_Ada2012 && Lang >= dwarf::DW_LANG_C89) ||
   (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
  "Invalid Language tag");
 
Index: llvm/include/llvm/BinaryFormat/Dwarf.h
===
--- llvm/include/llvm/BinaryFormat/Dwarf.h
+++ llvm/include/llvm/BinaryFormat/Dwarf.h
@@ -216,6 +216,8 @@
   case DW_LANG_C_plus_plus_03:
   case DW_LANG_C_plus_plus_11:
   case DW_LANG_C_plus_plus_14:
+  case DW_LANG_C_plus_plus_17:
+  case DW_LANG_C_plus_plus_20:
 result = true;
 break;
   case DW_LANG_C89:
@@ -256,6 +258,13 @@
   case DW_LANG_BORLAND_Delphi:
   case DW_LANG_lo_user:
   case DW_LANG_hi_user:
+  case DW_LANG_Kotlin:
+  case DW_LANG_Zig:
+  case DW_LANG_Crystal:
+  case DW_LANG_C17:
+  case DW_LANG_Fortran18:
+  case DW_LANG_Ada2005:
+  case DW_LANG_Ada2012:
 result = false;
 break;
   }
@@ -274,6 +283,7 @@
   case DW_LANG_Fortran95:
   case DW_LANG_Fortran03:
   case DW_LANG_Fortran08:
+  case DW_LANG_Fortran18:
 result = true;
 break;
   case DW_LANG_C89:
@@ -313,6 +323,14 @@
   case DW_LANG_BORLAND_Delphi:
   case DW_LANG_lo_user:
   case DW_LANG_hi_user:
+  case DW_LANG_Kotlin:
+  case DW_LANG_Zig:
+  case DW_LANG_Crystal:
+  case DW_LANG_C_plus_plus_17:
+  case DW_LANG_C_plus_plus_20:
+  case DW_LANG_C17:
+  case DW_LANG_Ada2005:
+  case DW_LANG_Ada2012:
 result = false;
 break;
   }
Index: llvm/include/llvm/BinaryFormat/Dwarf.def

[PATCH] D138939: [WIP][clang] adds a way to provide user-oriented reasons

2022-12-01 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb added a comment.

In D138939#3964677 , @erichkeane 
wrote:

> In D138939#3964439 , @erichkeane 
> wrote:
>
>> In D138939#3964404 , @cjdb wrote:
>>
>>> In D138939#3963496 , @erichkeane 
>>> wrote:
>>>
 In D138939#3963473 , @tschuett 
 wrote:

> Maybe `void FormatDiagnostic(SmallVectorImpl , 
> DiagnosticMode mode)`instead of `void 
> FormatDiagnostic(SmallVectorImpl )`?
> To make the transition easer and future proof.

 I like this idea.  Perhaps with DiagnosticMode being a 3-way enum:

   enum struct DiagnosticMode {
 Legacy,
 Sarif,  
 Default = Legacy
   }

 I like the idea in particular, since it makes a command line flag to 
 modify "Default" to be whichever the user prefers pretty trivial.
>>>
>>> There's already a flag for this: `-fdiagnostics-format=sarif`. Why do we 
>>> need a second diagnostic mode flag?
>>
>> Ah, oh... is the Sarif formatting being done with a new formatter?  That 
>> seems unfortunate, since folks using the other formatters won't be able to 
>> use the user friendly formats.
>
> I've been alerted offline that I am misunderstanding the Sarif proposal, and 
> where this is going.  I'll note that I wasn't present/invited at the calls 
> where all of this was discussed, so I am admittedly not completely up to 
> date.  The above concern shouldn't stop others from reviewing this, 
> particularly if you better understand the intent here.

I don't necessarily think you're the one misunderstanding here. We're 
definitely talking past one another, but I think it's equally likely that 
you're asking for something reasonable, and I'm mixing it up with something 
else.




Comment at: clang/include/clang/Frontend/DiagnosticRenderer.h:130
   /// \param Message The diagnostic message to emit.
+  /// \param Reason Supplementary information for the message.
   /// \param Ranges The underlined ranges for this code snippet.

rymiel wrote:
> Which parameter is this doxygen comment referring to?
Thanks, that was from an old iteration of the CL.



Comment at: clang/lib/Basic/Diagnostic.cpp:791
 
 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
 /// formal arguments into the %0 slots.  The result is appended onto the Str

erichkeane wrote:
> Comment no longer matches.
I've deleted the comment because it's already in the header, and risks going 
stale over and over.



Comment at: clang/test/Frontend/sarif-reason.cpp:15
+void g() {
+  f1<0>(); // expected-error{{no matching function for call to 'f1'}}
+  f1(); // expected-error{{no matching function for call to 'f1'}}

erichkeane wrote:
> This is definitely a case where I'd love the diagnostics formatted/arranged 
> differently here.  If you can use the #BOOKMARK style to make sure errors and 
> notes are together, it would better illustrate what you're trying to do here.
This is maybe done? I'm not sure if this is the #BOOKMARK style you're 
referring to, but it should capture the same intent. Lemme know if you had 
something else in mind and I'll happily change it  


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138939

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


[PATCH] D138939: [WIP][clang] adds a way to provide user-oriented reasons

2022-12-01 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb updated this revision to Diff 479492.
cjdb marked 4 inline comments as done.
cjdb added a comment.

responds to feedback


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138939

Files:
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/clangd/Compiler.cpp
  clang-tools-extra/clangd/Diagnostics.cpp
  clang/include/clang/Basic/Diagnostic.h
  clang/include/clang/Basic/Diagnostic.td
  clang/include/clang/Basic/DiagnosticAST.h
  clang/include/clang/Basic/DiagnosticAnalysis.h
  clang/include/clang/Basic/DiagnosticComment.h
  clang/include/clang/Basic/DiagnosticCrossTU.h
  clang/include/clang/Basic/DiagnosticDriver.h
  clang/include/clang/Basic/DiagnosticFrontend.h
  clang/include/clang/Basic/DiagnosticIDs.h
  clang/include/clang/Basic/DiagnosticLex.h
  clang/include/clang/Basic/DiagnosticParse.h
  clang/include/clang/Basic/DiagnosticRefactoring.h
  clang/include/clang/Basic/DiagnosticSema.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/DiagnosticSerialization.h
  clang/include/clang/Basic/PartialDiagnostic.h
  clang/include/clang/Frontend/ASTUnit.h
  clang/lib/Basic/Diagnostic.cpp
  clang/lib/Basic/DiagnosticIDs.cpp
  clang/lib/Format/TokenAnalyzer.cpp
  clang/lib/Frontend/ASTUnit.cpp
  clang/lib/Frontend/LogDiagnosticPrinter.cpp
  clang/lib/Frontend/SARIFDiagnosticPrinter.cpp
  clang/lib/Frontend/SerializedDiagnosticPrinter.cpp
  clang/lib/Frontend/TextDiagnosticBuffer.cpp
  clang/lib/Frontend/TextDiagnosticPrinter.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/test/Frontend/sarif-reason.cpp
  clang/test/TableGen/DiagnosticBase.inc
  clang/test/TableGen/deferred-diag.td
  clang/tools/clang-format/ClangFormat.cpp
  clang/tools/clang-import-test/clang-import-test.cpp
  clang/tools/diagtool/DiagnosticNames.cpp
  clang/unittests/Driver/SimpleDiagnosticConsumer.h
  clang/unittests/Driver/ToolChainTest.cpp
  clang/unittests/Frontend/FrontendActionTest.cpp
  clang/unittests/Tooling/RewriterTestContext.h
  clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
  flang/lib/Frontend/TextDiagnosticBuffer.cpp
  flang/lib/Frontend/TextDiagnosticPrinter.cpp
  libcxxabi/test/test_demangle.pass.cpp
  lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp

Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -697,7 +697,7 @@
 const clang::Diagnostic ) override {
 if (m_log) {
   llvm::SmallVector diag_str(10);
-  info.FormatDiagnostic(diag_str);
+  info.FormatLegacyDiagnostic(diag_str);
   diag_str.push_back('\0');
   LLDB_LOGF(m_log, "Compiler diagnostic: %s\n", diag_str.data());
 }
Index: lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
===
--- lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
+++ lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
@@ -192,7 +192,7 @@
   Log *log = GetLog(LLDBLog::Expressions);
   if (log) {
 llvm::SmallVector diag_str;
-Info.FormatDiagnostic(diag_str);
+Info.FormatLegacyDiagnostic(diag_str);
 diag_str.push_back('\0');
 const char *plain_diag = diag_str.data();
 LLDB_LOG(log, "Received diagnostic outside parsing: {0}", plain_diag);
Index: flang/lib/Frontend/TextDiagnosticPrinter.cpp
===
--- flang/lib/Frontend/TextDiagnosticPrinter.cpp
+++ flang/lib/Frontend/TextDiagnosticPrinter.cpp
@@ -37,7 +37,8 @@
   // Render the diagnostic message into a temporary buffer eagerly. We'll use
   // this later as we print out the diagnostic to the terminal.
   llvm::SmallString<100> outStr;
-  info.FormatDiagnostic(outStr);
+  info.FormatSummary(outStr);
+  info.FormatLegacyDiagnostic(outStr);
 
   llvm::raw_svector_ostream diagMessageStream(outStr);
 
Index: flang/lib/Frontend/TextDiagnosticBuffer.cpp
===
--- flang/lib/Frontend/TextDiagnosticBuffer.cpp
+++ flang/lib/Frontend/TextDiagnosticBuffer.cpp
@@ -29,7 +29,8 @@
   DiagnosticConsumer::HandleDiagnostic(level, info);
 
   llvm::SmallString<100> buf;
-  info.FormatDiagnostic(buf);
+  info.FormatSummary(buf);
+  info.FormatLegacyDiagnostic(buf);
   switch (level) {
   default:
 llvm_unreachable("Diagnostic not handled during diagnostic buffering!");
Index: clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
===
--- clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
+++ clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
@@ -604,7 

[PATCH] D118743: [clang-tidy] Add `modernize-use-inline-const-variables-in-headers` check

2022-12-01 Thread Lounarok via Phabricator via cfe-commits
Lounarok added a comment.

I tried this patch and it's really helpful!

However I found that it warns when it comes to `constexpr static` variable.

Snippet: `constexpr static int UNDEFINED_ERROR{0};`
Warning msg: `warning: global constant 'UNDEFINED_ERROR' should be marked as 
'inline' [modernize-use-inline-const-variables-in-headers]`
According to this ,  "A 
constexpr specifier used in a function or static data member (since C++17) 
declaration implies inline."

Just a notification up here, I'm fine with `// constexpr implies inline, just 
ignore inline const warning
// NOLINTNEXTLINE(modernize-use-inline-const-variables-in-headers)`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118743

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


[PATCH] D139148: Fix nullptr dereference found by Coverity static analysis tool

2022-12-01 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added a comment.

This looks like the correct thing to do but I see further down there are also 
unconditional uses of `Initializer` that should also be guarded with a check. 
It would be good to fix those as well since we are here.

I am guessing the answer is no since this was found using a static analysis 
tool but do you have a test case that triggers this failure?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139148

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


[PATCH] D137995: [Flang][Driver] Handle target CPU and features

2022-12-01 Thread Usman Nadeem via Phabricator via cfe-commits
mnadeem updated this revision to Diff 479474.
mnadeem marked 4 inline comments as done.
mnadeem added a comment.

- Address comments.
- Add fc1 tests.


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

https://reviews.llvm.org/D137995

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.h
  clang/lib/Driver/ToolChains/Flang.cpp
  clang/lib/Driver/ToolChains/Flang.h
  flang/include/flang/Frontend/TargetOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/target-cpu-features.f90

Index: flang/test/Driver/target-cpu-features.f90
===
--- /dev/null
+++ flang/test/Driver/target-cpu-features.f90
@@ -0,0 +1,56 @@
+! REQUIRES: aarch64-registered-target, x86-registered-target
+
+! Test that -mcpu/march are used and that the -target-cpu and -target-features
+! are also added to the fc1 command.
+
+! RUN: %flang --target=aarch64-linux-gnu -mcpu=cortex-a57 -c %s -### 2>&1 \
+! RUN: | FileCheck %s -check-prefix=CHECK-A57
+
+! RUN: %flang --target=aarch64-linux-gnu -mcpu=cortex-a76 -c %s -### 2>&1 \
+! RUN: | FileCheck %s -check-prefix=CHECK-A76
+
+! RUN: %flang --target=aarch64-linux-gnu -march=armv9 -c %s -### 2>&1 \
+! RUN: | FileCheck %s -check-prefix=CHECK-ARMV9
+
+! Negative test. ARM cpu with x86 target.
+! RUN: %flang --target=x86_64-linux-gnu -mcpu=cortex-a57 -c %s -### 2>&1 \
+! RUN: | FileCheck %s -check-prefix=CHECK-NO-A57
+
+! RUN: %flang --target=x86_64-linux-gnu -march=skylake -c %s -### 2>&1 \
+! RUN: | FileCheck %s -check-prefix=CHECK-SKYLAKE
+
+! RUN: %flang --target=x86_64h-linux-gnu -c %s -### 2>&1 \
+! RUN: | FileCheck %s -check-prefix=CHECK-X86_64H
+
+
+! Test that invalid cpu and features are ignored.
+
+! RUN: %flang_fc1 -triple aarch64-linux-gnu -target-cpu supercpu \
+! RUN: -o /dev/null -S %s 2>&1 | FileCheck %s -check-prefix=CHECK-INVALID-CPU
+
+! RUN: %flang_fc1 -triple aarch64-linux-gnu -target-feature +superspeed \
+! RUN: -o /dev/null -S %s 2>&1 | FileCheck %s -check-prefix=CHECK-INVALID-FEATURE
+
+
+! CHECK-A57: "-fc1" "-triple" "aarch64-unknown-linux-gnu"
+! CHECK-A57-SAME: "-target-cpu" "cortex-a57" "-target-feature" "+v8a" "-target-feature" "+crc" "-target-feature" "+crypto" "-target-feature" "+fp-armv8" "-target-feature" "+neon" "-target-feature" "+sha2" "-target-feature" "+aes"
+
+! CHECK-A76: "-fc1" "-triple" "aarch64-unknown-linux-gnu"
+! CHECK-A76-SAME: "-target-cpu" "cortex-a76" "-target-feature" "+v8.2a" "-target-feature" "+crc" "-target-feature" "+lse" "-target-feature" "+rdm" "-target-feature" "+crypto" "-target-feature" "+dotprod" "-target-feature" "+fp-armv8" "-target-feature" "+neon" "-target-feature" "+fullfp16" "-target-feature" "+ras" "-target-feature" "+rcpc" "-target-feature" "+ssbs" "-target-feature" "+sha2" "-target-feature" "+aes"
+
+! CHECK-ARMV9: "-fc1" "-triple" "aarch64-unknown-linux-gnu"
+! CHECK-ARMV9-SAME: "-target-cpu" "generic" "-target-feature" "+neon" "-target-feature" "+v9a" "-target-feature" "+sve" "-target-feature" "+sve2"
+
+! CHECK-NO-A57: "-fc1" "-triple" "x86_64-unknown-linux-gnu"
+! CHECK-NO-A57-NOT: cortex-a57
+! CHECK-NO-A57-SAME: "-target-cpu" "x86-64"
+! CHECK-NO-A57-NOT: cortex-a57
+
+! CHECK-SKYLAKE: "-fc1" "-triple" "x86_64-unknown-linux-gnu"
+! CHECK-SKYLAKE-SAME: "-target-cpu" "skylake"
+
+! CHECK-X86_64H: "-fc1" "-triple" "x86_64h-unknown-linux-gnu"
+! CHECK-X86_64H-SAME: "-target-cpu" "x86-64" "-target-feature" "-rdrnd" "-target-feature" "-aes" "-target-feature" "-pclmul" "-target-feature" "-rtm" "-target-feature" "-fsgsbase"
+
+! CHECK-INVALID-CPU: 'supercpu' is not a recognized processor for this target (ignoring processor)
+! CHECK-INVALID-FEATURE: '+superspeed' is not a recognized feature for this target (ignoring feature)
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -156,6 +156,8 @@
 ! HELP-FC1-NEXT: -P Disable linemarker output in -E mode
 ! HELP-FC1-NEXT: -std=   Language standard to compile for
 ! HELP-FC1-NEXT: -S Only run preprocess and compilation steps
+! HELP-FC1-NEXT: -target-cpu Target a specific cpu type
+! HELP-FC1-NEXT: -target-feature  Target specific attributes
 ! HELP-FC1-NEXT: -test-io   Run the InputOuputTest action. Use for development and testing only.
 ! HELP-FC1-NEXT: -triple Specify target triple (e.g. i686-apple-darwin9)
 ! HELP-FC1-NEXT: -U  Undefine macro 
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -591,7 +591,8 @@
 void 

[PATCH] D135841: [clang][deps][lex] Avoid canonicalization of remapped framework directories

2022-12-01 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir added inline comments.



Comment at: clang/lib/Lex/ModuleMap.cpp:1331
+auto CanonicalDirEntry = FM.getDirectory(CanonicalDir);
+if (CanonicalDirEntry && *CanonicalDirEntry == *DirEntry) {
+  bool Done = llvm::sys::path::replace_path_prefix(Path, Dir, 
CanonicalDir);

benlangmuir wrote:
> Wouldn't this indicate the particular VFS has a bug? 
^ Sorry this question was an old draft, you can disregard.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135841

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


[PATCH] D135841: [clang][deps][lex] Avoid canonicalization of remapped framework directories

2022-12-01 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir accepted this revision.
benlangmuir added a comment.
This revision is now accepted and ready to land.

Please add a comment about why this equality check is necessary.




Comment at: clang/lib/Lex/ModuleMap.cpp:1331
+auto CanonicalDirEntry = FM.getDirectory(CanonicalDir);
+if (CanonicalDirEntry && *CanonicalDirEntry == *DirEntry) {
+  bool Done = llvm::sys::path::replace_path_prefix(Path, Dir, 
CanonicalDir);

Wouldn't this indicate the particular VFS has a bug? 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135841

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


[PATCH] D139029: [clang-format] Don't move comments if AlignTrailingComments: Kind: Leave

2022-12-01 Thread Owen Pan via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGad83bead3d42: [clang-format] Dont move comments if 
AlignTrailingComments: Leave (authored by mairacanal, committed by owenpan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139029

Files:
  clang/lib/Format/WhitespaceManager.cpp
  clang/unittests/Format/FormatTestComments.cpp


Index: clang/unittests/Format/FormatTestComments.cpp
===
--- clang/unittests/Format/FormatTestComments.cpp
+++ clang/unittests/Format/FormatTestComments.cpp
@@ -3062,6 +3062,61 @@
"int d;// comment\n",
Style));
 
+  EXPECT_EQ("// do not touch\n"
+"int a;  // any comments\n"
+"\n"
+"   // comment\n"
+"// comment\n"
+"\n"
+"// comment",
+format("// do not touch\n"
+   "int a;  // any comments\n"
+   "\n"
+   "   // comment\n"
+   "// comment\n"
+   "\n"
+   "// comment",
+   Style));
+
+  EXPECT_EQ("// do not touch\n"
+"int a;  // any comments\n"
+"\n"
+"   // comment\n"
+"// comment\n"
+"\n"
+"// comment",
+format("// do not touch\n"
+   "int a;  // any comments\n"
+   "\n"
+   "\n"
+   "   // comment\n"
+   "// comment\n"
+   "\n"
+   "\n"
+   "// comment",
+   Style));
+
+  // Allow to keep 2 empty lines
+  Style.MaxEmptyLinesToKeep = 2;
+  EXPECT_EQ("// do not touch\n"
+"int a;  // any comments\n"
+"\n"
+"\n"
+"   // comment\n"
+"// comment\n"
+"\n"
+"// comment",
+format("// do not touch\n"
+   "int a;  // any comments\n"
+   "\n"
+   "\n"
+   "   // comment\n"
+   "// comment\n"
+   "\n"
+   "// comment",
+   Style));
+  Style.MaxEmptyLinesToKeep = 1;
+
   // Just format comments normally when leaving exceeds the column limit
   Style.ColumnLimit = 35;
   EXPECT_EQ("int foo = 12345; // comment\n"
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -957,7 +957,8 @@
 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Leave) {
   auto OriginalSpaces =
   Changes[i].OriginalWhitespaceRange.getEnd().getRawEncoding() -
-  Changes[i].OriginalWhitespaceRange.getBegin().getRawEncoding();
+  Changes[i].OriginalWhitespaceRange.getBegin().getRawEncoding() -
+  Changes[i].Tok->NewlinesBefore;
   unsigned RestoredLineLength = Changes[i].StartOfTokenColumn +
 Changes[i].TokenLength + OriginalSpaces;
   // If leaving comments makes the line exceed the column limit, give up to


Index: clang/unittests/Format/FormatTestComments.cpp
===
--- clang/unittests/Format/FormatTestComments.cpp
+++ clang/unittests/Format/FormatTestComments.cpp
@@ -3062,6 +3062,61 @@
"int d;// comment\n",
Style));
 
+  EXPECT_EQ("// do not touch\n"
+"int a;  // any comments\n"
+"\n"
+"   // comment\n"
+"// comment\n"
+"\n"
+"// comment",
+format("// do not touch\n"
+   "int a;  // any comments\n"
+   "\n"
+   "   // comment\n"
+   "// comment\n"
+   "\n"
+   "// comment",
+   Style));
+
+  EXPECT_EQ("// do not touch\n"
+"int a;  // any comments\n"
+"\n"
+"   // comment\n"
+"// comment\n"
+"\n"
+"// comment",
+format("// do not touch\n"
+   "int a;  // any comments\n"
+   "\n"
+   "\n"
+   "   // comment\n"
+   "// comment\n"
+   "\n"
+   "\n"
+   "// comment",
+   Style));
+
+  // Allow to keep 2 empty lines
+  Style.MaxEmptyLinesToKeep = 2;
+  EXPECT_EQ("// do not touch\n"
+"int a;  // any comments\n"
+"\n"
+"\n"
+"   // comment\n"
+"// comment\n"
+"\n"
+"// 

[clang] ad83bea - [clang-format] Don't move comments if AlignTrailingComments: Leave

2022-12-01 Thread Owen Pan via cfe-commits

Author: Maíra Canal
Date: 2022-12-01T16:07:06-08:00
New Revision: ad83bead3d42082f858d810a5b9f43ed096a6e3c

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

LOG: [clang-format] Don't move comments if AlignTrailingComments: Leave

For comments that start after a new line, currently, the comments are
being indented. This happens because the OriginalWhitespaceRange
considers newlines on the range. Therefore, when AlignTrailingComments:
Kind: Leave, deduct the number of newlines before the token to calculate
the number of spaces for trailing comments.

Fixes #59203.

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

Added: 


Modified: 
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTestComments.cpp

Removed: 




diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index ff7ef7edc984b..99261bdf4519e 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -957,7 +957,8 @@ void WhitespaceManager::alignTrailingComments() {
 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Leave) {
   auto OriginalSpaces =
   Changes[i].OriginalWhitespaceRange.getEnd().getRawEncoding() -
-  Changes[i].OriginalWhitespaceRange.getBegin().getRawEncoding();
+  Changes[i].OriginalWhitespaceRange.getBegin().getRawEncoding() -
+  Changes[i].Tok->NewlinesBefore;
   unsigned RestoredLineLength = Changes[i].StartOfTokenColumn +
 Changes[i].TokenLength + OriginalSpaces;
   // If leaving comments makes the line exceed the column limit, give up to

diff  --git a/clang/unittests/Format/FormatTestComments.cpp 
b/clang/unittests/Format/FormatTestComments.cpp
index 524bf87f37ba5..3336ee4f39efc 100644
--- a/clang/unittests/Format/FormatTestComments.cpp
+++ b/clang/unittests/Format/FormatTestComments.cpp
@@ -3062,6 +3062,61 @@ TEST_F(FormatTestComments, AlignTrailingCommentsLeave) {
"int d;// comment\n",
Style));
 
+  EXPECT_EQ("// do not touch\n"
+"int a;  // any comments\n"
+"\n"
+"   // comment\n"
+"// comment\n"
+"\n"
+"// comment",
+format("// do not touch\n"
+   "int a;  // any comments\n"
+   "\n"
+   "   // comment\n"
+   "// comment\n"
+   "\n"
+   "// comment",
+   Style));
+
+  EXPECT_EQ("// do not touch\n"
+"int a;  // any comments\n"
+"\n"
+"   // comment\n"
+"// comment\n"
+"\n"
+"// comment",
+format("// do not touch\n"
+   "int a;  // any comments\n"
+   "\n"
+   "\n"
+   "   // comment\n"
+   "// comment\n"
+   "\n"
+   "\n"
+   "// comment",
+   Style));
+
+  // Allow to keep 2 empty lines
+  Style.MaxEmptyLinesToKeep = 2;
+  EXPECT_EQ("// do not touch\n"
+"int a;  // any comments\n"
+"\n"
+"\n"
+"   // comment\n"
+"// comment\n"
+"\n"
+"// comment",
+format("// do not touch\n"
+   "int a;  // any comments\n"
+   "\n"
+   "\n"
+   "   // comment\n"
+   "// comment\n"
+   "\n"
+   "// comment",
+   Style));
+  Style.MaxEmptyLinesToKeep = 1;
+
   // Just format comments normally when leaving exceeds the column limit
   Style.ColumnLimit = 35;
   EXPECT_EQ("int foo = 12345; // comment\n"



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


[PATCH] D139154: [clang-doc] Add template support

2022-12-01 Thread Brett Wilson via Phabricator via cfe-commits
brettw created this revision.
brettw added a project: clang-tools-extra.
Herald added a project: All.
brettw requested review of this revision.
Herald added a subscriber: cfe-commits.

Decodes the template parameters for both functions and records.

For template specializations, records a reference to the main record that the 
specialization is of, and also the parameters that the code supplied to that 
template.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D139154

Files:
  clang-tools-extra/clang-doc/BitcodeReader.cpp
  clang-tools-extra/clang-doc/BitcodeWriter.cpp
  clang-tools-extra/clang-doc/BitcodeWriter.h
  clang-tools-extra/clang-doc/Representation.cpp
  clang-tools-extra/clang-doc/Representation.h
  clang-tools-extra/clang-doc/Serialize.cpp
  clang-tools-extra/clang-doc/YAMLGenerator.cpp

Index: clang-tools-extra/clang-doc/YAMLGenerator.cpp
===
--- clang-tools-extra/clang-doc/YAMLGenerator.cpp
+++ clang-tools-extra/clang-doc/YAMLGenerator.cpp
@@ -9,6 +9,7 @@
 //===--===//
 
 #include "Generators.h"
+#include "Representation.h"
 #include "llvm/Support/YAMLTraits.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -23,6 +24,7 @@
 LLVM_YAML_IS_SEQUENCE_VECTOR(FunctionInfo)
 LLVM_YAML_IS_SEQUENCE_VECTOR(EnumInfo)
 LLVM_YAML_IS_SEQUENCE_VECTOR(EnumValueInfo)
+LLVM_YAML_IS_SEQUENCE_VECTOR(TemplateParamInfo)
 LLVM_YAML_IS_SEQUENCE_VECTOR(TypedefInfo)
 LLVM_YAML_IS_SEQUENCE_VECTOR(BaseRecordInfo)
 LLVM_YAML_IS_SEQUENCE_VECTOR(std::unique_ptr)
@@ -142,6 +144,7 @@
   IO.mapOptional("ChildFunctions", I.Children.Functions);
   IO.mapOptional("ChildEnums", I.Children.Enums);
   IO.mapOptional("ChildTypedefs", I.Children.Typedefs);
+  IO.mapOptional("Template", I.Template);
 }
 
 static void CommentInfoMapping(IO , CommentInfo ) {
@@ -267,6 +270,28 @@
 // the AS that shouldn't be part of the output. Even though AS_public is the
 // default in the struct, it should be displayed in the YAML output.
 IO.mapOptional("Access", I.Access, clang::AccessSpecifier::AS_none);
+IO.mapOptional("Template", I.Template);
+  }
+};
+
+template <> struct MappingTraits {
+  static void mapping(IO , TemplateParamInfo ) {
+IO.mapOptional("Contents", I.Contents);
+  }
+};
+
+template <> struct MappingTraits {
+  static void mapping(IO , TemplateSpecializationInfo ) {
+IO.mapOptional("SpecializationOf", I.SpecializationOf);
+IO.mapOptional("Params", I.Params);
+  }
+};
+
+template <> struct MappingTraits {
+  static void mapping(IO , TemplateInfo ) {
+IO.mapOptional("Params", I.Params);
+IO.mapOptional("Specialization", I.Specialization,
+   Optional());
   }
 };
 
Index: clang-tools-extra/clang-doc/Serialize.cpp
===
--- clang-tools-extra/clang-doc/Serialize.cpp
+++ clang-tools-extra/clang-doc/Serialize.cpp
@@ -249,7 +249,8 @@
   } else {
 IT = InfoType::IT_default;
   }
-  return TypeInfo(Reference(getUSRForDecl(TD), TD->getNameAsString(), IT,
+  return TypeInfo(Reference(getUSRForDecl(TD),
+/*TD->getNameAsString()*/ T.getAsString(), IT,
 getInfoRelativePath(TD)));
 }
 
@@ -405,10 +406,7 @@
   for (const ParmVarDecl *P : D->parameters()) {
 FieldTypeInfo  = I.Params.emplace_back(
 getTypeInfoForType(P->getOriginalType()), P->getNameAsString());
-
-if (const Expr *DefaultArg = P->getDefaultArg()) {
-  FieldInfo.DefaultValue = getSourceCode(D, DefaultArg->getSourceRange());
-}
+FieldInfo.DefaultValue = getSourceCode(D, P->getDefaultArgRange());
   }
 }
 
@@ -476,6 +474,30 @@
 InfoType::IT_namespace);
 }
 
+void PopulateTemplateParameters(llvm::Optional ,
+const clang::Decl *D) {
+  if (const TemplateParameterList *ParamList =
+  D->getDescribedTemplateParams()) {
+if (!TemplateInfo) {
+  TemplateInfo.emplace();
+}
+for (const NamedDecl *ND : *ParamList) {
+  TemplateInfo->Params.emplace_back(
+  getSourceCode(ND, ND->getSourceRange()));
+}
+  }
+}
+
+TemplateParamInfo TemplateArgumentToInfo(const clang::Decl *D,
+ const TemplateArgument ) {
+  // The TemplateArgument's pretty printing handles all the normal cases
+  // well enough for our requirements.
+  std::string Str;
+  llvm::raw_string_ostream Stream(Str);
+  Arg.print(PrintingPolicy(D->getLangOpts()), Stream, false);
+  return TemplateParamInfo(Str);
+}
+
 template 
 static void populateInfo(Info , const T *D, const FullComment *C,
  bool ) {
@@ -508,6 +530,26 @@
  IsInAnonymousNamespace);
   I.ReturnType = getTypeInfoForType(D->getReturnType());
   parseParameters(I, D);
+
+  PopulateTemplateParameters(I.Template, D);
+
+  // Handle function template 

[PATCH] D138979: [NFC] Cleanup: Replaces BB->getInstList().splice() with BB->splice().

2022-12-01 Thread Vasileios Porpodas 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 rGbebca2b6d559: [NFC] Cleanup: Replaces 
BB-getInstList().splice() with BB-splice(). (authored by vporpo).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138979

Files:
  clang/lib/CodeGen/CGCleanup.cpp
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
  llvm/lib/IR/Instruction.cpp
  llvm/lib/Transforms/Coroutines/CoroSplit.cpp
  llvm/lib/Transforms/Scalar/LoopInterchange.cpp
  llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp
  llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
  llvm/lib/Transforms/Utils/CloneFunction.cpp
  llvm/lib/Transforms/Utils/FlattenCFG.cpp
  llvm/lib/Transforms/Utils/InlineFunction.cpp
  llvm/lib/Transforms/Utils/Local.cpp
  llvm/lib/Transforms/Utils/SimplifyCFG.cpp

Index: llvm/lib/Transforms/Utils/SimplifyCFG.cpp
===
--- llvm/lib/Transforms/Utils/SimplifyCFG.cpp
+++ llvm/lib/Transforms/Utils/SimplifyCFG.cpp
@@ -1603,16 +1603,13 @@
 // The debug location is an integral part of a debug info intrinsic
 // and can't be separated from it or replaced.  Instead of attempting
 // to merge locations, simply hoist both copies of the intrinsic.
-BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(),
-   I1);
-BIParent->getInstList().splice(BI->getIterator(), BB2->getInstList(),
-   I2);
+BIParent->splice(BI->getIterator(), BB1, I1->getIterator());
+BIParent->splice(BI->getIterator(), BB2, I2->getIterator());
   } else {
 // For a normal instruction, we just move one to right before the
 // branch, then replace all uses of the other with the first.  Finally,
 // we remove the now redundant second instruction.
-BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(),
-   I1);
+BIParent->splice(BI->getIterator(), BB1, I1->getIterator());
 if (!I2->use_empty())
   I2->replaceAllUsesWith(I1);
 I1->andIRFlags(I2);
@@ -3040,8 +3037,8 @@
   }
 
   // Hoist the instructions.
-  BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
-   ThenBB->begin(), std::prev(ThenBB->end()));
+  BB->splice(BI->getIterator(), ThenBB, ThenBB->begin(),
+ std::prev(ThenBB->end()));
 
   // Insert selects and rewrite the PHI operands.
   IRBuilder Builder(BI);
Index: llvm/lib/Transforms/Utils/Local.cpp
===
--- llvm/lib/Transforms/Utils/Local.cpp
+++ llvm/lib/Transforms/Utils/Local.cpp
@@ -799,7 +799,7 @@
 
   // Splice all the instructions from PredBB to DestBB.
   PredBB->getTerminator()->eraseFromParent();
-  DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
+  DestBB->splice(DestBB->begin(), PredBB);
   new UnreachableInst(PredBB->getContext(), PredBB);
 
   // If the PredBB is the entry block of the function, move DestBB up to
@@ -1204,8 +1204,7 @@
 
 // Copy over any phi, debug or lifetime instruction.
 BB->getTerminator()->eraseFromParent();
-Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
-   BB->getInstList());
+Succ->splice(Succ->getFirstNonPHI()->getIterator(), BB);
   } else {
 while (PHINode *PN = dyn_cast(>front())) {
   // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
@@ -2962,9 +2961,8 @@
 I->setDebugLoc(InsertPt->getDebugLoc());
 ++II;
   }
-  DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(),
- BB->begin(),
- BB->getTerminator()->getIterator());
+  DomBlock->splice(InsertPt->getIterator(), BB, BB->begin(),
+   BB->getTerminator()->getIterator());
 }
 
 namespace {
Index: llvm/lib/Transforms/Utils/InlineFunction.cpp
===
--- llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -2411,8 +2411,8 @@
   // Transfer all of the allocas over in a block.  Using splice means
   // that the instructions aren't removed from the symbol table, then
   // reinserted.
-  Caller->getEntryBlock().getInstList().splice(
-  InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I);
+  Caller->getEntryBlock().splice(InsertPoint, &*FirstNewBlock,
+ AI->getIterator(), I);
 }
   }
 
@@ -2755,8 +2755,8 @@
   // the calling basic block.
   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
 // Move all of the instructions right before the call.
-

[PATCH] D138255: [Driver] -p: change from unused warning to error for most targets

2022-12-01 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138255

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


[clang] bebca2b - [NFC] Cleanup: Replaces BB->getInstList().splice() with BB->splice().

2022-12-01 Thread Vasileios Porpodas via cfe-commits

Author: Vasileios Porpodas
Date: 2022-12-01T15:37:51-08:00
New Revision: bebca2b6d559f545c82047b2071273b4c243d13b

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

LOG: [NFC] Cleanup: Replaces BB->getInstList().splice() with BB->splice().

This is part of a series of cleanup patches towards making 
BasicBlock::getInstList() private.

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

Added: 


Modified: 
clang/lib/CodeGen/CGCleanup.cpp
llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
llvm/lib/IR/Instruction.cpp
llvm/lib/Transforms/Coroutines/CoroSplit.cpp
llvm/lib/Transforms/Scalar/LoopInterchange.cpp
llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp
llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
llvm/lib/Transforms/Utils/CloneFunction.cpp
llvm/lib/Transforms/Utils/FlattenCFG.cpp
llvm/lib/Transforms/Utils/InlineFunction.cpp
llvm/lib/Transforms/Utils/Local.cpp
llvm/lib/Transforms/Utils/SimplifyCFG.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGCleanup.cpp b/clang/lib/CodeGen/CGCleanup.cpp
index 5035ed34358d2..8ef2fb871956c 100644
--- a/clang/lib/CodeGen/CGCleanup.cpp
+++ b/clang/lib/CodeGen/CGCleanup.cpp
@@ -556,7 +556,7 @@ static llvm::BasicBlock 
*SimplifyCleanupEntry(CodeGenFunction ,
   Entry->replaceAllUsesWith(Pred);
 
   // Merge the blocks.
-  Pred->getInstList().splice(Pred->end(), Entry->getInstList());
+  Pred->splice(Pred->end(), Entry);
 
   // Kill the entry block.
   Entry->eraseFromParent();

diff  --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp 
b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
index 23a8895013de2..b0c8261c9addd 100644
--- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -261,8 +261,7 @@ void llvm::spliceBB(IRBuilderBase::InsertPoint IP, 
BasicBlock *New,
 
   // Move instructions to new block.
   BasicBlock *Old = IP.getBlock();
-  New->getInstList().splice(New->begin(), Old->getInstList(), IP.getPoint(),
-Old->end());
+  New->splice(New->begin(), Old, IP.getPoint(), Old->end());
 
   if (CreateBranch)
 BranchInst::Create(New, Old);

diff  --git a/llvm/lib/IR/Instruction.cpp b/llvm/lib/IR/Instruction.cpp
index 1dea11c6ea7d2..3988054f33bd2 100644
--- a/llvm/lib/IR/Instruction.cpp
+++ b/llvm/lib/IR/Instruction.cpp
@@ -115,7 +115,7 @@ void Instruction::moveAfter(Instruction *MovePos) {
 void Instruction::moveBefore(BasicBlock ,
  SymbolTableList::iterator I) {
   assert(I == BB.end() || I->getParent() == );
-  BB.getInstList().splice(I, getParent()->getInstList(), getIterator());
+  BB.splice(I, getParent(), getIterator());
 }
 
 bool Instruction::comesBefore(const Instruction *Other) const {

diff  --git a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp 
b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
index b54ece4ad1cdf..36ede8ebccc61 100644
--- a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
+++ b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
@@ -201,8 +201,8 @@ static bool replaceCoroEndAsync(AnyCoroEndInst *End) {
   assert(MustTailCallFuncBlock && "Must have a single predecessor block");
   auto It = MustTailCallFuncBlock->getTerminator()->getIterator();
   auto *MustTailCall = cast(&*std::prev(It));
-  CoroEndBlock->getInstList().splice(
-  End->getIterator(), MustTailCallFuncBlock->getInstList(), MustTailCall);
+  CoroEndBlock->splice(End->getIterator(), MustTailCallFuncBlock,
+   MustTailCall->getIterator());
 
   // Insert the return instruction.
   Builder.SetInsertPoint(End);

diff  --git a/llvm/lib/Transforms/Scalar/LoopInterchange.cpp 
b/llvm/lib/Transforms/Scalar/LoopInterchange.cpp
index 57e1b1c7c8182..a4ea93084c06c 100644
--- a/llvm/lib/Transforms/Scalar/LoopInterchange.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopInterchange.cpp
@@ -1350,11 +1350,10 @@ bool LoopInterchangeTransform::transform() {
 /// \brief Move all instructions except the terminator from FromBB right before
 /// InsertBefore
 static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) {
-  auto  = InsertBefore->getParent()->getInstList();
-  auto  = FromBB->getInstList();
+  BasicBlock *ToBB = InsertBefore->getParent();
 
-  ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(),
-FromBB->getTerminator()->getIterator());
+  ToBB->splice(InsertBefore->getIterator(), FromBB, FromBB->begin(),
+   FromBB->getTerminator()->getIterator());
 }
 
 /// Swap instructions between \p BB1 and \p BB2 but keep terminators intact.

diff  --git a/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp 
b/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp
index 35494e86996be..399aa635485ac 100644
--- a/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp
+++ 

[PATCH] D139029: [clang-format] Don't move comments if AlignTrailingComments: Kind: Leave

2022-12-01 Thread Maíra Canal via Phabricator via cfe-commits
mairacanal updated this revision to Diff 479455.
mairacanal marked 8 inline comments as done.
mairacanal added a comment.

Remove \n from the end of the test cases


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

https://reviews.llvm.org/D139029

Files:
  clang/lib/Format/WhitespaceManager.cpp
  clang/unittests/Format/FormatTestComments.cpp


Index: clang/unittests/Format/FormatTestComments.cpp
===
--- clang/unittests/Format/FormatTestComments.cpp
+++ clang/unittests/Format/FormatTestComments.cpp
@@ -3062,6 +3062,61 @@
"int d;// comment\n",
Style));
 
+  EXPECT_EQ("// do not touch\n"
+"int a;  // any comments\n"
+"\n"
+"   // comment\n"
+"// comment\n"
+"\n"
+"// comment",
+format("// do not touch\n"
+   "int a;  // any comments\n"
+   "\n"
+   "   // comment\n"
+   "// comment\n"
+   "\n"
+   "// comment",
+   Style));
+
+  EXPECT_EQ("// do not touch\n"
+"int a;  // any comments\n"
+"\n"
+"   // comment\n"
+"// comment\n"
+"\n"
+"// comment",
+format("// do not touch\n"
+   "int a;  // any comments\n"
+   "\n"
+   "\n"
+   "   // comment\n"
+   "// comment\n"
+   "\n"
+   "\n"
+   "// comment",
+   Style));
+
+  // Allow to keep 2 empty lines
+  Style.MaxEmptyLinesToKeep = 2;
+  EXPECT_EQ("// do not touch\n"
+"int a;  // any comments\n"
+"\n"
+"\n"
+"   // comment\n"
+"// comment\n"
+"\n"
+"// comment",
+format("// do not touch\n"
+   "int a;  // any comments\n"
+   "\n"
+   "\n"
+   "   // comment\n"
+   "// comment\n"
+   "\n"
+   "// comment",
+   Style));
+  Style.MaxEmptyLinesToKeep = 1;
+
   // Just format comments normally when leaving exceeds the column limit
   Style.ColumnLimit = 35;
   EXPECT_EQ("int foo = 12345; // comment\n"
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -957,7 +957,8 @@
 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Leave) {
   auto OriginalSpaces =
   Changes[i].OriginalWhitespaceRange.getEnd().getRawEncoding() -
-  Changes[i].OriginalWhitespaceRange.getBegin().getRawEncoding();
+  Changes[i].OriginalWhitespaceRange.getBegin().getRawEncoding() -
+  Changes[i].Tok->NewlinesBefore;
   unsigned RestoredLineLength = Changes[i].StartOfTokenColumn +
 Changes[i].TokenLength + OriginalSpaces;
   // If leaving comments makes the line exceed the column limit, give up to


Index: clang/unittests/Format/FormatTestComments.cpp
===
--- clang/unittests/Format/FormatTestComments.cpp
+++ clang/unittests/Format/FormatTestComments.cpp
@@ -3062,6 +3062,61 @@
"int d;// comment\n",
Style));
 
+  EXPECT_EQ("// do not touch\n"
+"int a;  // any comments\n"
+"\n"
+"   // comment\n"
+"// comment\n"
+"\n"
+"// comment",
+format("// do not touch\n"
+   "int a;  // any comments\n"
+   "\n"
+   "   // comment\n"
+   "// comment\n"
+   "\n"
+   "// comment",
+   Style));
+
+  EXPECT_EQ("// do not touch\n"
+"int a;  // any comments\n"
+"\n"
+"   // comment\n"
+"// comment\n"
+"\n"
+"// comment",
+format("// do not touch\n"
+   "int a;  // any comments\n"
+   "\n"
+   "\n"
+   "   // comment\n"
+   "// comment\n"
+   "\n"
+   "\n"
+   "// comment",
+   Style));
+
+  // Allow to keep 2 empty lines
+  Style.MaxEmptyLinesToKeep = 2;
+  EXPECT_EQ("// do not touch\n"
+"int a;  // any comments\n"
+"\n"
+"\n"
+"   // comment\n"
+"// comment\n"
+"\n"
+"// comment",
+format("// do not touch\n"
+   "int a;  // any comments\n"
+   "\n"
+   "\n"
+ 

[PATCH] D128372: [Clang-Tidy] Empty Check

2022-12-01 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

I just took a glance and the code looks reasonable.




Comment at: clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp:131
+bool HasClear = !Candidates.empty();
+
+if (HasClear) {

delete blank line



Comment at: clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp:160
+const Expr *Arg = NonMemberCall->getArg(0);
+
+CXXRecordDecl *ArgRecordDecl = Arg->getType()->getAsCXXRecordDecl();

delete blank line



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone/standalone-empty.cpp:161
+std::vector v;
+
+v.empty();

unneeded blank line

ditto below

They just make tests less compact without good values.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone/standalone-empty.cpp:177
+v.empty();
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: ignoring the result of 
'empty()'; did you mean 'clear()'? [bugprone-standalone-empty]
+// CHECK-FIXES: {{^  }}  v.clear();{{$}}

`[[@LINE-1]]` is deprecated lit syntax. Use `[[#@LINE-1]]`. Don't use the 
prevailing style in clang-tidy tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128372

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


[PATCH] D133392: [MTE] Add AArch64GlobalsTagging Pass

2022-12-01 Thread Mitch Phillips via Phabricator via cfe-commits
hctim added inline comments.



Comment at: llvm/lib/CodeGen/GlobalMerge.cpp:657
+// Tagged global variables shouldn't be merged, as they are assigned unique
+// memory tags at runtime.
+if (GV.isTagged())

eugenis wrote:
> This comment is not convincing. The change description is right that some 
> globals can be merged, copy that here, or extend the comment a little to 
> explain why and under what assumptions.
Thanks, extended the comment.



Comment at: llvm/lib/MC/ELFObjectWriter.cpp:1344
+  // when relocating `end` symbols, and this can only be determined by the
+  // attributes of the symbol itself.
+  if (Sym->isMemtag())

eugenis wrote:
> Isn't a bigger reason that we need to know the address tag to put on the 
> pointer, and that requires a symbol, not a section reference?
removed this comment here, as this was moved into the parent patch 
https://reviews.llvm.org/D131863 and the comment was updated there. this 
comment references the old st_other-based implementation, whereas now it's 
needed for SHT_AARCH64_MEMTAG_GLOBALS_STATIC.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133392

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


[PATCH] D133392: [MTE] Add AArch64GlobalsTagging Pass

2022-12-01 Thread Mitch Phillips via Phabricator via cfe-commits
hctim updated this revision to Diff 479452.
hctim marked 2 inline comments as done.
hctim added a comment.

Rebase now that the parent is submitted, clean up an old comment. New commit 
message also incoming.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133392

Files:
  clang/test/CodeGen/memtag-globals-asm.cpp
  llvm/lib/CodeGen/GlobalMerge.cpp
  llvm/lib/Target/AArch64/AArch64.h
  llvm/lib/Target/AArch64/AArch64GlobalsTagging.cpp
  llvm/lib/Target/AArch64/AArch64Subtarget.cpp
  llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
  llvm/lib/Target/AArch64/CMakeLists.txt
  llvm/test/CodeGen/AArch64/O0-pipeline.ll
  llvm/test/CodeGen/AArch64/O3-pipeline.ll

Index: llvm/test/CodeGen/AArch64/O3-pipeline.ll
===
--- llvm/test/CodeGen/AArch64/O3-pipeline.ll
+++ llvm/test/CodeGen/AArch64/O3-pipeline.ll
@@ -66,6 +66,7 @@
 ; CHECK-NEXT:   Expand reduction intrinsics
 ; CHECK-NEXT:   Natural Loop Information
 ; CHECK-NEXT:   TLS Variable Hoist
+; CHECK-NEXT: AArch64 Globals Tagging
 ; CHECK-NEXT: Stack Safety Analysis
 ; CHECK-NEXT:   FunctionPass Manager
 ; CHECK-NEXT: Dominator Tree Construction
Index: llvm/test/CodeGen/AArch64/O0-pipeline.ll
===
--- llvm/test/CodeGen/AArch64/O0-pipeline.ll
+++ llvm/test/CodeGen/AArch64/O0-pipeline.ll
@@ -26,6 +26,8 @@
 ; CHECK-NEXT:   Expand vector predication intrinsics
 ; CHECK-NEXT:   Scalarize Masked Memory Intrinsics
 ; CHECK-NEXT:   Expand reduction intrinsics
+; CHECK-NEXT: AArch64 Globals Tagging
+; CHECK-NEXT: FunctionPass Manager
 ; CHECK-NEXT:   AArch64 Stack Tagging
 ; CHECK-NEXT:   SME ABI Pass
 ; CHECK-NEXT:   Exception handling preparation
Index: llvm/lib/Target/AArch64/CMakeLists.txt
===
--- llvm/lib/Target/AArch64/CMakeLists.txt
+++ llvm/lib/Target/AArch64/CMakeLists.txt
@@ -56,6 +56,7 @@
   AArch64FastISel.cpp
   AArch64A53Fix835769.cpp
   AArch64FrameLowering.cpp
+  AArch64GlobalsTagging.cpp
   AArch64CompressJumpTables.cpp
   AArch64ConditionOptimizer.cpp
   AArch64RedundantCopyElimination.cpp
Index: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
===
--- llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
+++ llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
@@ -231,6 +231,7 @@
   initializeAArch64StackTaggingPass(*PR);
   initializeAArch64StackTaggingPreRAPass(*PR);
   initializeAArch64LowerHomogeneousPrologEpilogPass(*PR);
+  initializeAArch64GlobalsTaggingPass(*PR);
 }
 
 //===--===//
@@ -586,6 +587,7 @@
 
   TargetPassConfig::addIRPasses();
 
+  addPass(createAArch64GlobalsTaggingPass());
   addPass(createAArch64StackTaggingPass(
   /*IsOptNone=*/TM->getOptLevel() == CodeGenOpt::None));
 
Index: llvm/lib/Target/AArch64/AArch64Subtarget.cpp
===
--- llvm/lib/Target/AArch64/AArch64Subtarget.cpp
+++ llvm/lib/Target/AArch64/AArch64Subtarget.cpp
@@ -354,6 +354,13 @@
   if (TM.getCodeModel() == CodeModel::Large && isTargetMachO())
 return AArch64II::MO_GOT;
 
+  // All globals dynamically protected by MTE must have their address tags
+  // synthesized. This is done by having the loader stash the tag in the GOT
+  // entry. Force all tagged globals (even ones with internal linkage) through
+  // the GOT.
+  if (GV->isTagged())
+return AArch64II::MO_GOT;
+
   if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) {
 if (GV->hasDLLImportStorageClass()) {
   if (isWindowsArm64EC() && GV->getValueType()->isFunctionTy())
Index: llvm/lib/Target/AArch64/AArch64GlobalsTagging.cpp
===
--- /dev/null
+++ llvm/lib/Target/AArch64/AArch64GlobalsTagging.cpp
@@ -0,0 +1,144 @@
+//===- AArch64GlobalsTagging.cpp - Global tagging in IR ---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//===--===//
+
+#include "AArch64.h"
+#include "llvm/BinaryFormat/ELF.h"
+#include "llvm/IR/Attributes.h"
+#include "llvm/IR/Constants.h"
+#include "llvm/IR/GlobalValue.h"
+#include "llvm/IR/GlobalVariable.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/Module.h"
+#include "llvm/Pass.h"
+#include "llvm/Support/raw_ostream.h"
+
+#include 
+#include 
+
+using namespace llvm;
+
+static const Align kTagGranuleSize = Align(16);
+
+static bool shouldTagGlobal(GlobalVariable ) {
+  if 

[PATCH] D139045: [HIP] use detected GPU in --offload-arch

2022-12-01 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D139045#3964875 , @tra wrote:

> In any case, I think this is something that may need a wider forum.  Ask on 
> LLVM discourse?

RFC opened at discord 
https://discourse.llvm.org/t/rfc-let-clang-use-system-gpu-as-default-offload-arch-for-hip/66950


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

https://reviews.llvm.org/D139045

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


[PATCH] D137107: Allow MS extension: support of constexpr with __declspec(dllimport).

2022-12-01 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

To recap, I'm in favor of implementing dllimport constexpr global initializers 
with a high priority dynamic initializer. I would suggest using init_priority 
of 201 to run right after the "compiler" initializers.


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

https://reviews.llvm.org/D137107

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


[PATCH] D137603: [Clang][Sema] Fix attribute((format)) bug on non-variadic functions

2022-12-01 Thread Félix Cloutier via Phabricator via cfe-commits
fcloutier updated this revision to Diff 479427.
fcloutier added a comment.

Addressed Aaron's comment about fixits, ran clang-format.


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

https://reviews.llvm.org/D137603

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/FixIt/attr-format.c
  clang/test/Sema/attr-format.c

Index: clang/test/Sema/attr-format.c
===
--- clang/test/Sema/attr-format.c
+++ clang/test/Sema/attr-format.c
@@ -7,10 +7,14 @@
 void c(const char *a, ...) __attribute__((format(printf, 0, 2)));// expected-error {{'format' attribute parameter 2 is out of bounds}}
 void d(const char *a, int c) __attribute__((format(printf, 1, 2)));  // expected-warning {{GCC requires a function with the 'format' attribute to be variadic}}
 void e(char *str, int c, ...) __attribute__((format(printf, 2, 3))); // expected-error {{format argument not a string type}}
+void f(int a, const char *b, ...) __attribute__((format(printf, 2, 1))); // expected-error {{'format' attribute parameter 3 is out of bounds}}
+void g(int a, const char *b, ...) __attribute__((format(printf, 2, 2))); // expected-error {{'format' attribute parameter 3 is out of bounds}}
+void h(int a, const char *b, ...) __attribute__((format(printf, 2, 3))); // no-error
+void i(const char *a, int b, ...) __attribute__((format(printf, 1, 2))); // expected-error {{'format' attribute parameter 3 is out of bounds}}
 
 typedef const char *xpto;
-void f(xpto c, va_list list) __attribute__((format(printf, 1, 0))); // no-error
-void g(xpto c) __attribute__((format(printf, 1, 0)));   // no-error
+void j(xpto c, va_list list) __attribute__((format(printf, 1, 0))); // no-error
+void k(xpto c) __attribute__((format(printf, 1, 0)));   // no-error
 
 void y(char *str) __attribute__((format(strftime, 1, 0))); // no-error
 void z(char *str, int c, ...) __attribute__((format(strftime, 1, 2))); // expected-error {{strftime format attribute requires 3rd parameter to be 0}}
@@ -94,3 +98,9 @@
   forward_fixed(fmt, i);
   a(fmt, i);
 }
+
+__attribute__((format(printf, 1, 2))) void forward_fixed_2(const char *fmt, int i, int j) { // expected-warning{{GCC requires a function with the 'format' attribute to be variadic}}
+  forward_fixed_2(fmt, i, j);
+  a(fmt, i);
+}
+
Index: clang/test/FixIt/attr-format.c
===
--- /dev/null
+++ clang/test/FixIt/attr-format.c
@@ -0,0 +1,9 @@
+// RUN: not %clang_cc1 %s -fsyntax-only -fdiagnostics-parseable-fixits 2>&1 | FileCheck %s
+
+// CHECK: fix-it:"{{.*}}/attr-format.c":{4:36-4:37}:"0"
+__attribute__((format(strftime, 1, 1)))
+void my_strftime(const char *fmt);
+
+// CHECK: fix-it:"{{.*}}/attr-format.c":{8:34-8:36}:"2"
+__attribute__((format(printf, 1, 10)))
+void my_strftime(const char *fmt, ...);
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -3890,27 +3890,38 @@
   if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
 return;
 
-  // check if the function is variadic if the 3rd argument non-zero
+  // FirstArg == 0 is is always valid.
   if (FirstArg != 0) {
-if (isFunctionOrMethodVariadic(D))
-  ++NumArgs; // +1 for ...
-else
-  S.Diag(D->getLocation(), diag::warn_gcc_requires_variadic_function) << AL;
-  }
-
-  // strftime requires FirstArg to be 0 because it doesn't read from any
-  // variable the input is just the current time + the format string.
-  if (Kind == StrftimeFormat) {
-if (FirstArg != 0) {
+if (Kind == StrftimeFormat) {
+  // If the kind is strftime, FirstArg must be 0 because strftime does not
+  // use any variadic arguments.
   S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
-<< FirstArgExpr->getSourceRange();
-  return;
+  << FirstArgExpr->getSourceRange()
+  << FixItHint::CreateReplacement(FirstArgExpr->getSourceRange(), "0");
+  return;
+} else if (isFunctionOrMethodVariadic(D)) {
+  // Else, if the function is variadic, then FirstArg must be 0 or the
+  // "position" of the ... parameter. It's unusual to use 0 with variadic
+  // functions, so the fixit proposes the latter.
+  if (FirstArg != NumArgs + 1) {
+S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
+<< AL << 3 << FirstArgExpr->getSourceRange()
+<< FixItHint::CreateReplacement(FirstArgExpr->getSourceRange(),
+std::to_string(NumArgs + 1));
+return;
+  }
+} else {
+  // Inescapable GCC compatibility diagnostic.
+  S.Diag(D->getLocation(), diag::warn_gcc_requires_variadic_function) << AL;
+  if (FirstArg <= Idx) {
+// Else, the 

[clang-tools-extra] f885ae2 - clangd: Try to fix build with std::optional

2022-12-01 Thread Matt Arsenault via cfe-commits

Author: Matt Arsenault
Date: 2022-12-01T17:59:40-05:00
New Revision: f885ae231033877abcabf921815f75fae310f6bf

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

LOG: clangd: Try to fix build with std::optional

Should have been in e748db0f7f0971dc258c6631ae1fb0a38cfdf9dd, but the
build option is well hidden.

Added: 


Modified: 
clang-tools-extra/clangd/CompileCommands.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/CompileCommands.cpp 
b/clang-tools-extra/clangd/CompileCommands.cpp
index 3876cfce8316..2a808b4338b4 100644
--- a/clang-tools-extra/clangd/CompileCommands.cpp
+++ b/clang-tools-extra/clangd/CompileCommands.cpp
@@ -28,6 +28,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Program.h"
 #include 
+#include 
 #include 
 #include 
 



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


[PATCH] D138393: HIP: Directly call fabs builtins

2022-12-01 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl accepted this revision.
yaxunl added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks


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

https://reviews.llvm.org/D138393

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


[PATCH] D139148: Fix nullptr dereference found by Coverity static analysis tool

2022-12-01 Thread Sindhu Chittireddy via Phabricator via cfe-commits
schittir created this revision.
Herald added a project: All.
schittir requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Adding nullptr check for 'Initializer'


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D139148

Files:
  clang/lib/Sema/SemaInit.cpp


Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -5962,9 +5962,10 @@
 if (Kind.getKind() == InitializationKind::IK_Direct ||
 (Kind.getKind() == InitializationKind::IK_Copy &&
  (Context.hasSameUnqualifiedType(SourceType, DestType) ||
-  S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType
-  TryConstructorInitialization(S, Entity, Kind, Args,
-   DestType, DestType, *this);
+  (Initializer &&
+   S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, 
DestType)
+  TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
+   *this);
 // - Otherwise (i.e., for the remaining copy-initialization cases),
 //   user-defined conversion sequences that can convert from the source
 //   type to the destination type or (when a conversion function is


Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -5962,9 +5962,10 @@
 if (Kind.getKind() == InitializationKind::IK_Direct ||
 (Kind.getKind() == InitializationKind::IK_Copy &&
  (Context.hasSameUnqualifiedType(SourceType, DestType) ||
-  S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType
-  TryConstructorInitialization(S, Entity, Kind, Args,
-   DestType, DestType, *this);
+  (Initializer &&
+   S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType)
+  TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
+   *this);
 // - Otherwise (i.e., for the remaining copy-initialization cases),
 //   user-defined conversion sequences that can convert from the source
 //   type to the destination type or (when a conversion function is
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137534: [C++20] [Modules] [ClangScanDeps] Allow clang-scan-deps to without specified compilation database in P1689 (3/3)

2022-12-01 Thread Ben Boeckel via Phabricator via cfe-commits
ben.boeckel added a comment.

So a few things I see when trying to put this into CMake:

- P1689  output is only to `stdout`?
- Is there a way to get `-MF` output for the files read during scanning? This 
is useful to know that "header X changed, scanning may have changed, so please 
rerun scanning".

Other than that, I have success with CMake's test suite with this patchset as 
well as the patchset of D137059 .


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

https://reviews.llvm.org/D137534

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


[PATCH] D139029: [clang-format] Don't move comments if AlignTrailingComments: Kind: Leave

2022-12-01 Thread Owen Pan via Phabricator via cfe-commits
owenpan accepted this revision.
owenpan added a comment.

Please mark comments as done if you have addressed them.




Comment at: clang/unittests/Format/FormatTestComments.cpp:3071
+"\n"
+"// comment\n",
+format("// do not touch\n"





Comment at: clang/unittests/Format/FormatTestComments.cpp:3078
+   "\n"
+   "// comment\n",
+   Style));





Comment at: clang/unittests/Format/FormatTestComments.cpp:3087
+"\n"
+"// comment\n",
+format("// do not touch\n"





Comment at: clang/unittests/Format/FormatTestComments.cpp:3096
+   "\n"
+   "// comment\n",
+   Style));





Comment at: clang/unittests/Format/FormatTestComments.cpp:3108
+"\n"
+"// comment\n",
+format("// do not touch\n"





Comment at: clang/unittests/Format/FormatTestComments.cpp:3116
+   "\n"
+   "// comment\n",
+   Style));




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

https://reviews.llvm.org/D139029

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


[clang-tools-extra] f4fb2b3 - [clangd] Fix build after e748db0f7f0971dc258c6631ae1fb0a38cfdf9dd

2022-12-01 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-12-01T22:18:34Z
New Revision: f4fb2b3048c7e775df7b12a94cc41d490ca3b58e

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

LOG: [clangd] Fix build after e748db0f7f0971dc258c6631ae1fb0a38cfdf9dd

Added: 


Modified: 
clang-tools-extra/clangd/CompileCommands.cpp
clang-tools-extra/clangd/SystemIncludeExtractor.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/CompileCommands.cpp 
b/clang-tools-extra/clangd/CompileCommands.cpp
index e84eb0aa30328..3876cfce83165 100644
--- a/clang-tools-extra/clangd/CompileCommands.cpp
+++ b/clang-tools-extra/clangd/CompileCommands.cpp
@@ -46,11 +46,11 @@ llvm::Optional 
queryXcrun(llvm::ArrayRef Argv) {
   llvm::SmallString<64> OutFile;
   llvm::sys::fs::createTemporaryFile("clangd-xcrun", "", OutFile);
   llvm::FileRemover OutRemover(OutFile);
-  llvm::Optional Redirects[3] = {
+  std::optional Redirects[3] = {
   /*stdin=*/{""}, /*stdout=*/{OutFile.str()}, /*stderr=*/{""}};
   vlog("Invoking {0} to find clang installation", *Xcrun);
   int Ret = llvm::sys::ExecuteAndWait(*Xcrun, Argv,
-  /*Env=*/llvm::None, Redirects,
+  /*Env=*/std::nullopt, Redirects,
   /*SecondsToWait=*/10);
   if (Ret != 0) {
 log("xcrun exists but failed with code {0}. "

diff  --git a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp 
b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
index 7cfbd3dbf7318..2624b8fafcfc6 100644
--- a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
+++ b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
@@ -175,7 +175,7 @@ extractSystemIncludesAndTarget(llvm::SmallString<128> 
Driver,
   auto CleanUp = llvm::make_scope_exit(
   []() { llvm::sys::fs::remove(StdErrPath); });
 
-  llvm::Optional Redirects[] = {{""}, {""}, StdErrPath.str()};
+  std::optional Redirects[] = {{""}, {""}, StdErrPath.str()};
 
   llvm::SmallVector Args = {Driver, "-E", "-x",
  Lang,   "-",  "-v"};



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


[PATCH] D135750: [clang][Interp] Track initialization state of local variables

2022-12-01 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:835
 IsTemporary = true;
 Ty = E->getType();
   }

Do we really want to the type of the expression? If we have a `ValueDecl` don't 
we want that type? I think they should be the same, do you have any examples 
where the expression is the type we want? I am looking at the AST from ` int x 
= 1+1L;` 

https://godbolt.org/z/q3Tr7Kxoq



Comment at: clang/lib/AST/Interp/Descriptor.h:73
+  /// Flag indicating if the field is mutable (if in a record).
+  unsigned IsMutable : 1;
+

Maybe `IsFieldMutable` b/c we call `CreateDescriptor` it is a little confusing 
why we have `IsConst` and `IsMutable`



Comment at: clang/lib/AST/Interp/Pointer.h:63-64
 private:
   static constexpr unsigned PastEndMark = (unsigned)-1;
   static constexpr unsigned RootPtrMark = (unsigned)-1;
 

or `-1u`  



Comment at: clang/test/AST/Interp/cxx20.cpp:65
 }
-static_assert(unInitLocal() == 0, ""); // expected-error {{not an integral 
constant expression}} \
-   // ref-error {{not an integral constant 
expression}} \
-   // ref-note {{in call to 
'unInitLocal()'}}
-
-/// TODO: The example above is correctly rejected by the new constexpr
-///   interpreter, but for the wrong reasons. We don't reject it because
-///   it is an uninitialized read, we reject it simply because
-///   the local variable does not have an initializer.
-///
-///   The code below should be accepted but is also being rejected
-///   right now.
-#if 0
+static_assert(unInitLocal() == 0, ""); // ref-error {{not an integral constant 
expression}} \
+   // ref-note {{in call to 
'unInitLocal()'}} \

Can we also test local arrays and classes as well?


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

https://reviews.llvm.org/D135750

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


[clang] e748db0 - Support: Convert Program APIs to std::optional

2022-12-01 Thread Matt Arsenault via cfe-commits

Author: Matt Arsenault
Date: 2022-12-01T17:00:44-05:00
New Revision: e748db0f7f0971dc258c6631ae1fb0a38cfdf9dd

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

LOG: Support: Convert Program APIs to std::optional

Added: 


Modified: 
clang/include/clang/Driver/Compilation.h
clang/include/clang/Driver/Job.h
clang/lib/Driver/Compilation.cpp
clang/lib/Driver/Driver.cpp
clang/lib/Driver/Job.cpp
clang/lib/Driver/ToolChains/AMDGPU.cpp
clang/tools/clang-scan-deps/ClangScanDeps.cpp
llvm/include/llvm/Support/Program.h
llvm/lib/IR/PrintPasses.cpp
llvm/lib/Support/Program.cpp
llvm/lib/Support/Signals.cpp
llvm/lib/Support/Unix/Program.inc
llvm/lib/Support/Windows/Program.inc
llvm/tools/bugpoint/OptimizerDriver.cpp
llvm/tools/bugpoint/ToolRunner.cpp
llvm/tools/llvm-cov/CodeCoverage.cpp
llvm/tools/llvm-profgen/PerfReader.cpp
llvm/tools/llvm-reduce/TestRunner.cpp
llvm/unittests/Support/Host.cpp
llvm/unittests/Support/ProgramTest.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Compilation.h 
b/clang/include/clang/Driver/Compilation.h
index 842efda9f0774..f58b5a8cc9fdb 100644
--- a/clang/include/clang/Driver/Compilation.h
+++ b/clang/include/clang/Driver/Compilation.h
@@ -15,13 +15,13 @@
 #include "clang/Driver/Util.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
-#include "llvm/ADT/Optional.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Option/Option.h"
 #include 
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 
@@ -113,7 +113,7 @@ class Compilation {
   ArgStringMap FailureResultFiles;
 
   /// Optional redirection for stdin, stdout, stderr.
-  std::vector> Redirects;
+  std::vector> Redirects;
 
   /// Callback called after compilation job has been finished.
   /// Arguments of the callback are the compilation job as an instance of
@@ -332,8 +332,8 @@ class Compilation {
   ///
   /// \param Redirects - array of optional paths. The array should have a size
   /// of three. The inferior process's stdin(0), stdout(1), and stderr(2) will
-  /// be redirected to the corresponding paths, if provided (not llvm::None).
-  void Redirect(ArrayRef> Redirects);
+  /// be redirected to the corresponding paths, if provided (not std::nullopt).
+  void Redirect(ArrayRef> Redirects);
 };
 
 } // namespace driver

diff  --git a/clang/include/clang/Driver/Job.h 
b/clang/include/clang/Driver/Job.h
index 96cdd6fd957aa..01f8c42ef2cdb 100644
--- a/clang/include/clang/Driver/Job.h
+++ b/clang/include/clang/Driver/Job.h
@@ -12,13 +12,13 @@
 #include "clang/Basic/LLVM.h"
 #include "clang/Driver/InputInfo.h"
 #include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/Optional.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/iterator.h"
 #include "llvm/Option/Option.h"
 #include "llvm/Support/Program.h"
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -142,10 +142,10 @@ class Command {
   std::vector Environment;
 
   /// Optional redirection for stdin, stdout, stderr.
-  std::vector> RedirectFiles;
+  std::vector> RedirectFiles;
 
   /// Information on executable run provided by OS.
-  mutable Optional ProcStat;
+  mutable std::optional ProcStat;
 
   /// When a response file is needed, we try to put most arguments in an
   /// exclusive file, while others remains as regular command line arguments.
@@ -178,7 +178,7 @@ class Command {
   virtual void Print(llvm::raw_ostream , const char *Terminator, bool Quote,
  CrashReportInfo *CrashInfo = nullptr) const;
 
-  virtual int Execute(ArrayRef> Redirects,
+  virtual int Execute(ArrayRef> Redirects,
   std::string *ErrMsg, bool *ExecutionFailed) const;
 
   /// getSource - Return the Action which caused the creation of this job.
@@ -207,7 +207,8 @@ class Command {
   /// from the parent process will be used.
   virtual void setEnvironment(llvm::ArrayRef NewEnvironment);
 
-  void setRedirectFiles(const std::vector> );
+  void
+  setRedirectFiles(const std::vector> );
 
   void replaceArguments(llvm::opt::ArgStringList List) {
 Arguments = std::move(List);
@@ -225,7 +226,7 @@ class Command {
 return OutputFilenames;
   }
 
-  Optional getProcessStatistics() const {
+  std::optional getProcessStatistics() const {
 return ProcStat;
   }
 
@@ -245,7 +246,7 @@ class CC1Command : public Command {
   void Print(llvm::raw_ostream , const char *Terminator, bool Quote,
  CrashReportInfo *CrashInfo = nullptr) const override;
 
-  int Execute(ArrayRef> Redirects, std::string *ErrMsg,
+  int Execute(ArrayRef> Redirects, std::string 
*ErrMsg,
   bool *ExecutionFailed) const override;
 
   void setEnvironment(llvm::ArrayRef 

[PATCH] D139045: [HIP] use detected GPU in --offload-arch

2022-12-01 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

In D139045#3962354 , @yaxunl wrote:

> I understand your point. However, when users use gcc or clang and do not 
> specify target or CPU, the compiled program will execute on their system. 
> This is because gcc or clang has a default target and CPU that works for the 
> system. 
> This is not the case for HIP since the default gfx803 will not work for the 
> system unless the system happens to have a gfx803. 
> To let the users have a similar experience with the default target/CPU as 
> gcc/clang, HIP needs to assume the system GPU as the default. Users could 
> specify --offload-arch explicitly if they want to compile for certain GPU's.

This is not a new problem. I had the same problem with the choice of defaults 
for CUDA compilation and came to the conclusion that there's no such thing for 
GPUs and that the best we can do is to pick the most 'conservative' target. It 
may have worked for CUDA as PTX for an old GPU could in theory be JIT-compiled 
if the executable ran on a newer GPU, but the user is generally expected to 
specify the architectures they want to target. The default is, essentially, 
equally bad for everyone who happens to use it. In that sense `gfx803` or any 
other architecture would do that job just fine.

The auto-detection assumes that the host where the build is done is also the 
target the executable is going to run on. This is not true in many cases. 
I'd go as far as to say that in absolute terms most builds for GPUs out there 
are done on the machines without GPUs. 
Given the lack of a universally sensible default, I would prefer to require the 
user to explicitly specify the targets they want, with `auto/native` as an 
option.

On the other hand, OpenMP already appears to do some automagic detection of 
GPUs, so perhaps it is useful enough to do for HIP, too.

In any case, I think this is something that may need a wider forum.  Ask on 
LLVM discourse?


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

https://reviews.llvm.org/D139045

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


[PATCH] D138958: [clang] Better UX for Clang’s unwind-affecting attributes

2022-12-01 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri marked an inline comment as done.
lebedev.ri added inline comments.



Comment at: clang/lib/Analysis/CFG.cpp:2725
   NoReturn = true;
-if (FD->hasAttr())
+if (FD->hasAttr() || FD->hasAttr())
   AddEHEdge = false;

erichkeane wrote:
> lebedev.ri wrote:
> > erichkeane wrote:
> > > I find myself thinking we should probably have a function in FunctionDecl 
> > > that tests for the various states of the function, rather than keep 
> > > checking the attribute's presence.  
> > Yes, we have a huge spaghetti code spread through clang
> > that tries to answer the same two question:
> > 1. i'm a caller, if i call this function, might it throw?
> > 1. i'm a callee, what should i do with exceptions that try to unwind out of 
> > me?
> > 
> > I don't know how to improve that, and i don't think just moving this into 
> > FunctionDecl would help.
> > 
> `FunctionDecl::WontThrow` and `FunctionDecl::ShouldUnwind` ? 
As noted in the RFC, there are 3 possible behaviors on unwind.
If we want to improve interface, we should account for all of them.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138958

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


[PATCH] D138958: [clang] Better UX for Clang’s unwind-affecting attributes

2022-12-01 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

I'll take a look at rewording the docs if no one else does.  I should hopefully 
have time next week, the rest of the patch is perhaps more important at the 
moment.




Comment at: clang/docs/ReleaseNotes.rst:841
   operator.
-- ``clang_Cursor_getNumTemplateArguments``, 
``clang_Cursor_getTemplateArgumentKind``, 
-  ``clang_Cursor_getTemplateArgumentType``, 
``clang_Cursor_getTemplateArgumentValue`` and 
+- ``clang_Cursor_getNumTemplateArguments``, 
``clang_Cursor_getTemplateArgumentKind``,
+  ``clang_Cursor_getTemplateArgumentType``, 
``clang_Cursor_getTemplateArgumentValue`` and

lebedev.ri wrote:
> erichkeane wrote:
> > unrelated changes here?
> Having whitespaces before newline is bad :/
> This is editor doing so on file save,
> and my git complains otherwise.
Yep, i had to turn that off in my editor at one point because I did this!  I 
just pushed d5fc931ba to remove that WS, so this will disappear in your  next 
rebase.



Comment at: clang/lib/Analysis/CFG.cpp:2725
   NoReturn = true;
-if (FD->hasAttr())
+if (FD->hasAttr() || FD->hasAttr())
   AddEHEdge = false;

lebedev.ri wrote:
> erichkeane wrote:
> > I find myself thinking we should probably have a function in FunctionDecl 
> > that tests for the various states of the function, rather than keep 
> > checking the attribute's presence.  
> Yes, we have a huge spaghetti code spread through clang
> that tries to answer the same two question:
> 1. i'm a caller, if i call this function, might it throw?
> 1. i'm a callee, what should i do with exceptions that try to unwind out of 
> me?
> 
> I don't know how to improve that, and i don't think just moving this into 
> FunctionDecl would help.
> 
`FunctionDecl::WontThrow` and `FunctionDecl::ShouldUnwind` ? 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138958

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


[clang] d5fc931 - Remove some trailing WS from the release notes

2022-12-01 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2022-12-01T13:37:19-08:00
New Revision: d5fc931ba7d0b8f2bc0f78fe9266ca2bbc468736

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

LOG: Remove some trailing WS from the release notes

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ff97240e1322b..d9c1f42c01fb2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -839,8 +839,8 @@ libclang
 - Introduced the new function ``clang_CXXMethod_isMoveAssignmentOperator``,
   which identifies whether a method cursor is a move-assignment
   operator.
-- ``clang_Cursor_getNumTemplateArguments``, 
``clang_Cursor_getTemplateArgumentKind``, 
-  ``clang_Cursor_getTemplateArgumentType``, 
``clang_Cursor_getTemplateArgumentValue`` and 
+- ``clang_Cursor_getNumTemplateArguments``, 
``clang_Cursor_getTemplateArgumentKind``,
+  ``clang_Cursor_getTemplateArgumentType``, 
``clang_Cursor_getTemplateArgumentValue`` and
   ``clang_Cursor_getTemplateArgumentUnsignedValue`` now work on struct, class,
   and partial template specialization cursors in addition to function cursors.
 



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


[PATCH] D138958: [clang] Better UX for Clang’s unwind-affecting attributes

2022-12-01 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 479413.
lebedev.ri marked 5 inline comments as done.
lebedev.ri added a comment.

@erichkeane thank you for taking a look!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138958

Files:
  clang-tools-extra/clang-tidy/bugprone/ExceptionEscapeCheck.cpp
  clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/Builtins.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/Analysis/CFG.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/Sema/AnalysisBasedWarnings.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExceptionSpec.cpp
  clang/lib/Sema/SemaStmtAttr.cpp
  clang/test/CodeGen/function-attributes.c
  clang/test/CodeGen/struct-passing.c
  clang/test/CodeGenCXX/2009-05-04-PureConstNounwind.cpp
  clang/test/CodeGenCXX/exception-escape-RAII-codegen.cpp
  clang/test/CodeGenCXX/exception-escape-codegen.cpp
  clang/test/CodeGenCXX/pr58798.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/SemaCXX/warn-throw-out-noexcept-func.cpp

Index: clang/test/SemaCXX/warn-throw-out-noexcept-func.cpp
===
--- clang/test/SemaCXX/warn-throw-out-noexcept-func.cpp
+++ clang/test/SemaCXX/warn-throw-out-noexcept-func.cpp
@@ -9,12 +9,12 @@
   int i;
   ~B_ShouldDiag() noexcept(true) {} //no disg, no throw stmt
 };
-struct R_ShouldDiag : A_ShouldDiag {
+struct R_ShouldDiag_NoThrow : A_ShouldDiag {
   B_ShouldDiag b;
-  ~R_ShouldDiag() { // expected-note  {{destructor has a implicit non-throwing exception specification}}
+  ~R_ShouldDiag_NoThrow() { // expected-note  {{destructor has a implicit non-throwing exception specification}}
 throw 1; // expected-warning {{has a non-throwing exception specification but}}
   }
-  __attribute__((nothrow)) R_ShouldDiag() {// expected-note {{function declared non-throwing here}}
+  __attribute__((nothrow)) R_ShouldDiag_NoThrow() {// expected-note {{function declared non-throwing here}}
 throw 1;// expected-warning {{has a non-throwing exception specification but}}
   }
   void __attribute__((nothrow)) SomeThrow() {// expected-note {{function declared non-throwing here}}
@@ -24,6 +24,18 @@
throw 1; // expected-warning {{has a non-throwing exception specification but}}
   }
 };
+struct R_ShouldDiag_NoUnwind : A_ShouldDiag {
+  B_ShouldDiag b;
+  ~R_ShouldDiag_NoUnwind() { // expected-note  {{destructor has a implicit non-throwing exception specification}}
+throw 1; // expected-warning {{has a non-throwing exception specification but}}
+  }
+  __attribute__((nounwind)) R_ShouldDiag_NoUnwind() {// expected-note {{function declared non-throwing here}}
+throw 1;// expected-warning {{has a non-throwing exception specification but}}
+  }
+  void __attribute__((nounwind)) SomeThrow() {// expected-note {{function declared non-throwing here}}
+   throw 1; // expected-warning {{has a non-throwing exception specification but}}
+  }
+};
 
 struct M_ShouldNotDiag {
   B_ShouldDiag b;
@@ -240,7 +252,7 @@
   }
 }
 // As seen in p34973, this should not throw the warning.  If there is an active
-// exception, catch(...) catches everything. 
+// exception, catch(...) catches everything.
 void o_ShouldNotDiag() noexcept {
   try {
 throw;
Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -115,6 +115,7 @@
 // CHECK-NEXT: NoStackProtector (SubjectMatchRule_function)
 // CHECK-NEXT: NoThreadSafetyAnalysis (SubjectMatchRule_function)
 // CHECK-NEXT: NoThrow (SubjectMatchRule_hasType_functionType)
+// CHECK-NEXT: NoUnwind (SubjectMatchRule_function)
 // CHECK-NEXT: NoUwtable (SubjectMatchRule_hasType_functionType)
 // CHECK-NEXT: NotTailCalled (SubjectMatchRule_function)
 // CHECK-NEXT: OSConsumed (SubjectMatchRule_variable_is_parameter)
Index: clang/test/CodeGenCXX/pr58798.cpp
===
--- clang/test/CodeGenCXX/pr58798.cpp
+++ /dev/null
@@ -1,186 +0,0 @@
-// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --check-attributes
-// RUN: %clang_cc1 -emit-llvm %s -o - -triple x86_64-linux-gnu -fexceptions -fcxx-exceptions | FileCheck %s
-
-// CHECK: Function Attrs: mustprogress noinline nounwind optnone willreturn memory(read)
-// CHECK-LABEL: define {{[^@]+}}@_Z54early_caller_of_callee_with_clang_attr_with_clang_attri
-// CHECK-SAME: (i32 noundef [[A:%.*]]) #[[ATTR0:[0-9]+]] {
-// 

[PATCH] D138958: [clang] Better UX for Clang’s unwind-affecting attributes

2022-12-01 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:841
   operator.
-- ``clang_Cursor_getNumTemplateArguments``, 
``clang_Cursor_getTemplateArgumentKind``, 
-  ``clang_Cursor_getTemplateArgumentType``, 
``clang_Cursor_getTemplateArgumentValue`` and 
+- ``clang_Cursor_getNumTemplateArguments``, 
``clang_Cursor_getTemplateArgumentKind``,
+  ``clang_Cursor_getTemplateArgumentType``, 
``clang_Cursor_getTemplateArgumentValue`` and

erichkeane wrote:
> unrelated changes here?
Having whitespaces before newline is bad :/
This is editor doing so on file save,
and my git complains otherwise.



Comment at: clang/include/clang/Basic/AttrDocs.td:560
+
+A function declared with ``__attribute__((const))`` attribute can not have
+infinite loops (i.e. they must either terminate or return to the caller,

erichkeane wrote:
> Similar changes to above.  This attribute is more of an 'assertion' by the 
> developer that they promise they don't do these things (and we will UB 
> otherwise), so I think they need to be written from that perspective.
> 
> I might suggest making an attempt to reword these docs.
> 
> ALSO, since these attributes can be spelled `clang::pure` and `clang::const` 
> (IIRC?), I'd suggest we make the documents spelling-agnostic other than in 
> direct code examples.
> I might suggest making an attempt to reword these docs.

This is my best attempt :)
If you can propose a better wording,
please feel free to do so.



Comment at: clang/lib/Analysis/CFG.cpp:2725
   NoReturn = true;
-if (FD->hasAttr())
+if (FD->hasAttr() || FD->hasAttr())
   AddEHEdge = false;

erichkeane wrote:
> I find myself thinking we should probably have a function in FunctionDecl 
> that tests for the various states of the function, rather than keep checking 
> the attribute's presence.  
Yes, we have a huge spaghetti code spread through clang
that tries to answer the same two question:
1. i'm a caller, if i call this function, might it throw?
1. i'm a callee, what should i do with exceptions that try to unwind out of me?

I don't know how to improve that, and i don't think just moving this into 
FunctionDecl would help.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138958

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


[PATCH] D139113: Fix a couple additional cases in misc-use-anonymous-namespace

2022-12-01 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp updated this revision to Diff 479409.
carlosgalvezp retitled this revision from "Fix a couple additional cases in 
misc-use-anonymous-namespace only" to "Fix a couple additional cases in 
misc-use-anonymous-namespace".
carlosgalvezp edited the summary of this revision.
carlosgalvezp added a comment.

Fix typo in commit message


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139113

Files:
  clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp
  clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
  clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
  
clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
  clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
@@ -1,4 +1,5 @@
-// RUN: %check_clang_tidy %s misc-use-anonymous-namespace %t
+// RUN: %check_clang_tidy %s misc-use-anonymous-namespace %t -- -header-filter=.* -- -I%S/Inputs
+#include "use-anonymous-namespace.h"
 
 static void f1();
 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: function 'f1' declared 'static', move to anonymous namespace instead [misc-use-anonymous-namespace]
@@ -57,3 +58,7 @@
 {
   static int x;
 }
+
+// OK
+static const int v8{123};
+static constexpr int v9{123};
Index: clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
@@ -0,0 +1,3 @@
+// Should not warn here, do not require anonymous namespaces in headers
+static int gv{123};
+static void gf(){}
Index: clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
+++ clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
@@ -13,6 +13,14 @@
 keep C compatibility [1]. ``static`` is an overloaded term with different meanings in
 different contexts, so it can create confusion.
 
+The following uses of ``static`` will *not* be diagnosed:
+
+* Functions or variables in header files, since anonymous namespaces in headers
+  is considered an antipattern. Allowed header file extensions can be configured
+  via the `HeaderFileExtensions` option (see below).
+* ``const`` or ``constexpr`` variables, since they already have implicit internal
+  linkage in C++.
+
 Examples:
 
 .. code-block:: c++
@@ -41,4 +49,14 @@
 int x;
   }  // namespace
 
+Options
+---
+
+.. option:: HeaderFileExtensions
+
+   A semicolon-separated list of filename extensions of header files (the filename
+   extensions should not include "." prefix). Default is ";h;hh;hpp;hxx".
+   For extension-less header files, using an empty string or leaving an
+   empty string between ";" if there are other filename extensions.
+
 [1] `Undeprecating static `_
Index: clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
===
--- clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
+++ clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_USEANONYMOUSNAMESPACECHECK_H
 
 #include "../ClangTidyCheck.h"
+#include "../utils/FileExtensionsUtils.h"
 
 namespace clang {
 namespace tidy {
@@ -19,19 +20,29 @@
 /// suggests moving them to an anonymous namespace. It also suggests removing
 /// 'static' if they are already inside an anonymous namespace.
 ///
+/// The check supports these options:
+///   - `HeaderFileExtensions`: a semicolon-separated list of filename
+/// extensions of header files (The filename extension should not contain
+/// "." prefix). ";h;hh;hpp;hxx" by default.
+///
+/// For extension-less header files, using an empty string or leaving an
+/// empty string between ";" if there are other filename extensions.
+///
 /// For the user-facing documentation see:
 /// http://clang.llvm.org/extra/clang-tidy/checks/modernize/use-anonymous-namespace.html
 class UseAnonymousNamespaceCheck : public ClangTidyCheck {
 public:
-  UseAnonymousNamespaceCheck(StringRef Name, ClangTidyContext *Context)
-  : ClangTidyCheck(Name, Context) {}
+  UseAnonymousNamespaceCheck(StringRef Name, ClangTidyContext *Context);
   bool isLanguageVersionSupported(const LangOptions ) const override {
 return LangOpts.CPlusPlus;
   }
+  void 

[PATCH] D139113: Fix a couple additional cases in misc-use-anonymous-namespace only

2022-12-01 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp marked an inline comment as done.
carlosgalvezp added a comment.

> The LLVM coding style says to prefer static over anonymous namespaces.

Yes, but this is not an LLVM check, it's a `misc` check. Other project are 
allowed to have other guidelines.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139113

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


[PATCH] D139113: Fix a couple additional cases in misc-use-anonymous-namespace only

2022-12-01 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp updated this revision to Diff 479403.
carlosgalvezp added a comment.

Fix typo


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139113

Files:
  clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp
  clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
  clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
  
clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
  clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
@@ -1,4 +1,5 @@
-// RUN: %check_clang_tidy %s misc-use-anonymous-namespace %t
+// RUN: %check_clang_tidy %s misc-use-anonymous-namespace %t -- -header-filter=.* -- -I%S/Inputs
+#include "use-anonymous-namespace.h"
 
 static void f1();
 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: function 'f1' declared 'static', move to anonymous namespace instead [misc-use-anonymous-namespace]
@@ -57,3 +58,7 @@
 {
   static int x;
 }
+
+// OK
+static const int v8{123};
+static constexpr int v9{123};
Index: clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
@@ -0,0 +1,3 @@
+// Should not warn here, do not require anonymous namespaces in headers
+static int gv{123};
+static void gf(){}
Index: clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
+++ clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
@@ -13,6 +13,14 @@
 keep C compatibility [1]. ``static`` is an overloaded term with different meanings in
 different contexts, so it can create confusion.
 
+The following uses of ``static`` will *not* be diagnosed:
+
+* Functions or variables in header files, since anonymous namespaces in headers
+  is considered an antipattern. Allowed header file extensions can be configured
+  via the `HeaderFileExtensions` option (see below).
+* ``const`` or ``constexpr`` variables, since they already have implicit internal
+  linkage in C++.
+
 Examples:
 
 .. code-block:: c++
@@ -41,4 +49,14 @@
 int x;
   }  // namespace
 
+Options
+---
+
+.. option:: HeaderFileExtensions
+
+   A semicolon-separated list of filename extensions of header files (the filename
+   extensions should not include "." prefix). Default is ";h;hh;hpp;hxx".
+   For extension-less header files, using an empty string or leaving an
+   empty string between ";" if there are other filename extensions.
+
 [1] `Undeprecating static `_
Index: clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
===
--- clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
+++ clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_USEANONYMOUSNAMESPACECHECK_H
 
 #include "../ClangTidyCheck.h"
+#include "../utils/FileExtensionsUtils.h"
 
 namespace clang {
 namespace tidy {
@@ -19,19 +20,29 @@
 /// suggests moving them to an anonymous namespace. It also suggests removing
 /// 'static' if they are already inside an anonymous namespace.
 ///
+/// The check supports these options:
+///   - `HeaderFileExtensions`: a semicolon-separated list of filename
+/// extensions of header files (The filename extension should not contain
+/// "." prefix). ";h;hh;hpp;hxx" by default.
+///
+/// For extension-less header files, using an empty string or leaving an
+/// empty string between ";" if there are other filename extensions.
+///
 /// For the user-facing documentation see:
 /// http://clang.llvm.org/extra/clang-tidy/checks/modernize/use-anonymous-namespace.html
 class UseAnonymousNamespaceCheck : public ClangTidyCheck {
 public:
-  UseAnonymousNamespaceCheck(StringRef Name, ClangTidyContext *Context)
-  : ClangTidyCheck(Name, Context) {}
+  UseAnonymousNamespaceCheck(StringRef Name, ClangTidyContext *Context);
   bool isLanguageVersionSupported(const LangOptions ) const override {
 return LangOpts.CPlusPlus;
   }
+  void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
 
 private:
+  const StringRef 

[PATCH] D139113: Fix a couple additional cases in misc-use-anonymous-namespace only

2022-12-01 Thread Thorsten via Phabricator via cfe-commits
tschuett added a comment.

The LLVM coding style says to prefer static over anonymous namespaces.




Comment at: 
clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst:19
+* Functions or variables in header files, since anonymous namespaces in headers
+  is considered an antipattern. Allowed header file exntensions can be 
configured
+  via the `HeaderFileExtensions` option (see below).

extensions


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139113

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


[PATCH] D139113: Fix a couple additional cases in misc-use-anonymous-namespace only

2022-12-01 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added a comment.

I'm happy with my changes now, ready for a new round of review! :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139113

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


[PATCH] D136554: Implement CWG2631

2022-12-01 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

@aaron.ballman if you don't scream, I'll probably try again this week end. I 
did multiple stage 2 full builds to be sure this time. The fix is pretty small 
but the investigation took a while...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136554

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


[PATCH] D139113: Fix a couple additional cases in misc-use-anonymous-namespace only

2022-12-01 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp updated this revision to Diff 479397.
carlosgalvezp added a comment.

Remove accidentally added newline.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139113

Files:
  clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp
  clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
  clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
  
clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
  clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
@@ -1,4 +1,5 @@
-// RUN: %check_clang_tidy %s misc-use-anonymous-namespace %t
+// RUN: %check_clang_tidy %s misc-use-anonymous-namespace %t -- -header-filter=.* -- -I%S/Inputs
+#include "use-anonymous-namespace.h"
 
 static void f1();
 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: function 'f1' declared 'static', move to anonymous namespace instead [misc-use-anonymous-namespace]
@@ -57,3 +58,7 @@
 {
   static int x;
 }
+
+// OK
+static const int v8{123};
+static constexpr int v9{123};
Index: clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
@@ -0,0 +1,3 @@
+// Should not warn here, do not require anonymous namespaces in headers
+static int gv{123};
+static void gf(){}
Index: clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
+++ clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
@@ -13,6 +13,14 @@
 keep C compatibility [1]. ``static`` is an overloaded term with different meanings in
 different contexts, so it can create confusion.
 
+The following uses of ``static`` will *not* be diagnosed:
+
+* Functions or variables in header files, since anonymous namespaces in headers
+  is considered an antipattern. Allowed header file exntensions can be configured
+  via the `HeaderFileExtensions` option (see below).
+* ``const`` or ``constexpr`` variables, since they already have implicit internal
+  linkage in C++.
+
 Examples:
 
 .. code-block:: c++
@@ -41,4 +49,14 @@
 int x;
   }  // namespace
 
+Options
+---
+
+.. option:: HeaderFileExtensions
+
+   A semicolon-separated list of filename extensions of header files (the filename
+   extensions should not include "." prefix). Default is ";h;hh;hpp;hxx".
+   For extension-less header files, using an empty string or leaving an
+   empty string between ";" if there are other filename extensions.
+
 [1] `Undeprecating static `_
Index: clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
===
--- clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
+++ clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_USEANONYMOUSNAMESPACECHECK_H
 
 #include "../ClangTidyCheck.h"
+#include "../utils/FileExtensionsUtils.h"
 
 namespace clang {
 namespace tidy {
@@ -19,19 +20,29 @@
 /// suggests moving them to an anonymous namespace. It also suggests removing
 /// 'static' if they are already inside an anonymous namespace.
 ///
+/// The check supports these options:
+///   - `HeaderFileExtensions`: a semicolon-separated list of filename
+/// extensions of header files (The filename extension should not contain
+/// "." prefix). ";h;hh;hpp;hxx" by default.
+///
+/// For extension-less header files, using an empty string or leaving an
+/// empty string between ";" if there are other filename extensions.
+///
 /// For the user-facing documentation see:
 /// http://clang.llvm.org/extra/clang-tidy/checks/modernize/use-anonymous-namespace.html
 class UseAnonymousNamespaceCheck : public ClangTidyCheck {
 public:
-  UseAnonymousNamespaceCheck(StringRef Name, ClangTidyContext *Context)
-  : ClangTidyCheck(Name, Context) {}
+  UseAnonymousNamespaceCheck(StringRef Name, ClangTidyContext *Context);
   bool isLanguageVersionSupported(const LangOptions ) const override {
 return LangOpts.CPlusPlus;
   }
+  void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
 
 private:
+  const 

[PATCH] D136554: Implement CWG2631

2022-12-01 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 479395.
cor3ntin added a comment.



- Member initializers wwere not marked odr used properly
- Fixing that unearthed an other bug:  consteval calls in a nested member 
initializers were not properly detected if the member was list initialized to 
its default value (`= {}`).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136554

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/ExprCXX.h
  clang/include/clang/AST/Stmt.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/Decl.cpp
  clang/lib/AST/ExprCXX.cpp
  clang/lib/Parse/ParseCXXInlineMethods.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Sema/UsedDeclVisitor.h
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/test/CXX/class/class.local/p1-0x.cpp
  clang/test/CXX/drs/dr26xx.cpp
  clang/test/CodeGenCXX/builtin-source-location.cpp
  clang/test/CodeGenCXX/default-arguments-with-immediate.cpp
  clang/test/CodeGenCXX/meminit-initializers-odr.cpp
  clang/test/PCH/default-argument-with-immediate-calls.cpp
  clang/test/SemaCXX/cxx11-default-member-initializers.cpp
  clang/test/SemaCXX/cxx2a-consteval-default-params.cpp
  clang/test/SemaCXX/source_location.cpp
  clang/www/cxx_dr_status.html

Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -15594,7 +15594,7 @@
 https://wg21.link/cwg2631;>2631
 DR
 Immediate function evaluations in default arguments
-Unknown
+Clang 16
   
   
 https://wg21.link/cwg2632;>2632
Index: clang/test/SemaCXX/source_location.cpp
===
--- clang/test/SemaCXX/source_location.cpp
+++ clang/test/SemaCXX/source_location.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -std=c++1z -fcxx-exceptions -fexceptions -verify %s
+// RUN: %clang_cc1 -std=c++2a -fcxx-exceptions -DUSE_CONSTEVAL -fexceptions -verify %s
 // expected-no-diagnostics
 
 #define assert(...) ((__VA_ARGS__) ? ((void)0) : throw 42)
@@ -8,15 +9,22 @@
 template 
 struct Printer;
 
+#ifdef USE_CONSTEVAL
+#define SOURCE_LOC_EVAL_KIND consteval
+#else
+#define SOURCE_LOC_EVAL_KIND constexpr
+#endif
+
 namespace std {
 class source_location {
   struct __impl;
 
 public:
-  static constexpr source_location current(const __impl *__p = __builtin_source_location()) noexcept {
-source_location __loc;
-__loc.__m_impl = __p;
-return __loc;
+  static SOURCE_LOC_EVAL_KIND source_location
+current(const __impl *__p = __builtin_source_location()) noexcept {
+  source_location __loc;
+  __loc.__m_impl = __p;
+  return __loc;
   }
   constexpr source_location() = default;
   constexpr source_location(source_location const &) = default;
@@ -593,3 +601,51 @@
   }
   static_assert(test());
 }
+
+namespace Lambda {
+#line 8000 "TestLambda.cpp"
+constexpr int nested_lambda(int l = []{
+  return SL::current().line();
+}()) {
+  return l;
+}
+static_assert(nested_lambda() == __LINE__ - 4);
+
+constexpr int lambda_param(int l = [](int l = SL::current().line()) {
+  return l;
+}()) {
+  return l;
+}
+static_assert(lambda_param() == __LINE__);
+
+
+}
+
+constexpr int compound_literal_fun(int a =
+  (int){ SL::current().line() }
+) { return a ;}
+static_assert(compound_literal_fun() == __LINE__);
+
+struct CompoundLiteral {
+  int a = (int){ SL::current().line() };
+};
+static_assert(CompoundLiteral{}.a == __LINE__);
+
+
+// FIXME
+// Init captures are subexpressions of the lambda expression
+// so according to the standard immediate invocations in init captures
+// should be evaluated at the call site.
+// However Clang does not yet implement this as it would introduce
+// a fair bit of complexity.
+// We intend to implement that functionality once we find real world
+// use cases that require it.
+constexpr int test_init_capture(int a =
+[b = SL::current().line()] { return b; }()) {
+  return a;
+}
+#ifdef USE_CONSTEVAL
+static_assert(test_init_capture() == __LINE__ - 4);
+#else
+static_assert(test_init_capture() == __LINE__ );
+#endif
Index: clang/test/SemaCXX/cxx2a-consteval-default-params.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/cxx2a-consteval-default-params.cpp
@@ -0,0 +1,81 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++20 %s
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++2b %s
+
+consteval int undefined();  // expected-note 4 {{declared here}}
+
+void check_lambdas_unused(
+int a = []
+{
+// The body of a lambda is not a subexpression of the lambda

[PATCH] D139113: Fix a couple additional cases in misc-use-anonymous-namespace only

2022-12-01 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp updated this revision to Diff 479394.
carlosgalvezp added a comment.

Document ignored cases in the documentation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139113

Files:
  clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp
  clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
  clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
  
clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
  clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
@@ -1,4 +1,5 @@
-// RUN: %check_clang_tidy %s misc-use-anonymous-namespace %t
+// RUN: %check_clang_tidy %s misc-use-anonymous-namespace %t -- -header-filter=.* -- -I%S/Inputs
+#include "use-anonymous-namespace.h"
 
 static void f1();
 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: function 'f1' declared 'static', move to anonymous namespace instead [misc-use-anonymous-namespace]
@@ -57,3 +58,7 @@
 {
   static int x;
 }
+
+// OK
+static const int v8{123};
+static constexpr int v9{123};
Index: clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
@@ -0,0 +1,3 @@
+// Should not warn here, do not require anonymous namespaces in headers
+static int gv{123};
+static void gf(){}
Index: clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
+++ clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
@@ -13,6 +13,14 @@
 keep C compatibility [1]. ``static`` is an overloaded term with different meanings in
 different contexts, so it can create confusion.
 
+The following uses of ``static`` will *not* be diagnosed:
+
+* Functions or variables in header files, since anonymous namespaces in headers
+  is considered an antipattern. Allowed header file exntensions can be configured
+  via the `HeaderFileExtensions` option (see below).
+* ``const`` or ``constexpr`` variables, since they already have implicit internal
+  linkage in C++.
+
 Examples:
 
 .. code-block:: c++
@@ -41,4 +49,14 @@
 int x;
   }  // namespace
 
+Options
+---
+
+.. option:: HeaderFileExtensions
+
+   A semicolon-separated list of filename extensions of header files (the filename
+   extensions should not include "." prefix). Default is ";h;hh;hpp;hxx".
+   For extension-less header files, using an empty string or leaving an
+   empty string between ";" if there are other filename extensions.
+
 [1] `Undeprecating static `_
Index: clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
===
--- clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
+++ clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_USEANONYMOUSNAMESPACECHECK_H
 
 #include "../ClangTidyCheck.h"
+#include "../utils/FileExtensionsUtils.h"
 
 namespace clang {
 namespace tidy {
@@ -19,19 +20,29 @@
 /// suggests moving them to an anonymous namespace. It also suggests removing
 /// 'static' if they are already inside an anonymous namespace.
 ///
+/// The check supports these options:
+///   - `HeaderFileExtensions`: a semicolon-separated list of filename
+/// extensions of header files (The filename extension should not contain
+/// "." prefix). ";h;hh;hpp;hxx" by default.
+///
+/// For extension-less header files, using an empty string or leaving an
+/// empty string between ";" if there are other filename extensions.
+///
 /// For the user-facing documentation see:
 /// http://clang.llvm.org/extra/clang-tidy/checks/modernize/use-anonymous-namespace.html
 class UseAnonymousNamespaceCheck : public ClangTidyCheck {
 public:
-  UseAnonymousNamespaceCheck(StringRef Name, ClangTidyContext *Context)
-  : ClangTidyCheck(Name, Context) {}
+  UseAnonymousNamespaceCheck(StringRef Name, ClangTidyContext *Context);
   bool isLanguageVersionSupported(const LangOptions ) const override {
 return LangOpts.CPlusPlus;
   }
+  void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
 
 private:
+  

[PATCH] D137346: [-Wunsafe-buffer-usage] Initial commit - Transition away from raw buffer accesses.

2022-12-01 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

Ok I added D136811  as a parent revision but 
I don't think it makes sense to land D136811  
before this patch, given that D136811 's 
documentation does not *yet* reflect the actual state of things. I think we 
should start landing patches, and land the documentation later when we think it 
actually makes sense to inform people about the warning and encourage enabling 
it.


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

https://reviews.llvm.org/D137346

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


[PATCH] D139113: Fix a couple additional cases in misc-use-anonymous-namespace only

2022-12-01 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp updated this revision to Diff 479391.
carlosgalvezp marked an inline comment as done.
carlosgalvezp added a comment.

Add options for users to define their own header file
extensions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139113

Files:
  clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp
  clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
  clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
  
clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
  clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
@@ -1,4 +1,5 @@
-// RUN: %check_clang_tidy %s misc-use-anonymous-namespace %t
+// RUN: %check_clang_tidy %s misc-use-anonymous-namespace %t -- -header-filter=.* -- -I%S/Inputs
+#include "use-anonymous-namespace.h"
 
 static void f1();
 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: function 'f1' declared 'static', move to anonymous namespace instead [misc-use-anonymous-namespace]
@@ -57,3 +58,7 @@
 {
   static int x;
 }
+
+// OK
+static const int v8{123};
+static constexpr int v9{123};
Index: clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
@@ -0,0 +1,3 @@
+// Should not warn here, do not require anonymous namespaces in headers
+static int gv{123};
+static void gf(){}
Index: clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
+++ clang-tools-extra/docs/clang-tidy/checks/misc/use-anonymous-namespace.rst
@@ -41,4 +41,14 @@
 int x;
   }  // namespace
 
+Options
+---
+
+.. option:: HeaderFileExtensions
+
+   A semicolon-separated list of filename extensions of header files (the filename
+   extensions should not include "." prefix). Default is ";h;hh;hpp;hxx".
+   For extension-less header files, using an empty string or leaving an
+   empty string between ";" if there are other filename extensions.
+
 [1] `Undeprecating static `_
Index: clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
===
--- clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
+++ clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_USEANONYMOUSNAMESPACECHECK_H
 
 #include "../ClangTidyCheck.h"
+#include "../utils/FileExtensionsUtils.h"
 
 namespace clang {
 namespace tidy {
@@ -19,19 +20,29 @@
 /// suggests moving them to an anonymous namespace. It also suggests removing
 /// 'static' if they are already inside an anonymous namespace.
 ///
+/// The check supports these options:
+///   - `HeaderFileExtensions`: a semicolon-separated list of filename
+/// extensions of header files (The filename extension should not contain
+/// "." prefix). ";h;hh;hpp;hxx" by default.
+///
+/// For extension-less header files, using an empty string or leaving an
+/// empty string between ";" if there are other filename extensions.
+///
 /// For the user-facing documentation see:
 /// http://clang.llvm.org/extra/clang-tidy/checks/modernize/use-anonymous-namespace.html
 class UseAnonymousNamespaceCheck : public ClangTidyCheck {
 public:
-  UseAnonymousNamespaceCheck(StringRef Name, ClangTidyContext *Context)
-  : ClangTidyCheck(Name, Context) {}
+  UseAnonymousNamespaceCheck(StringRef Name, ClangTidyContext *Context);
   bool isLanguageVersionSupported(const LangOptions ) const override {
 return LangOpts.CPlusPlus;
   }
+  void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
 
 private:
+  const StringRef RawStringHeaderFileExtensions;
+  utils::FileExtensionsSet HeaderFileExtensions;
   template  void processMatch(const T *MatchedDecl);
 };
 
Index: clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp
===
--- clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp
+++ clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp
@@ -21,10 +21,20 @@
   return Node.getStorageClass() == SC_Static;
 }
 

[PATCH] D127284: [clang-repl] Support statements on global scope in incremental mode.

2022-12-01 Thread Vassil Vassilev via Phabricator via cfe-commits
v.g.vassilev updated this revision to Diff 479390.
v.g.vassilev added a comment.
Herald added a subscriber: arphaman.

Fixed the diff. I accidentally have added the commits from 
https://reviews.llvm.org/D139016


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

https://reviews.llvm.org/D127284

Files:
  clang/include/clang/AST/ASTNodeTraverser.h
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/DeclNodes.td
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/include/clang/Lex/Preprocessor.h
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Sema/Template.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/lib/AST/Decl.cpp
  clang/lib/AST/DeclBase.cpp
  clang/lib/AST/DeclPrinter.cpp
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/lib/CodeGen/ModuleBuilder.cpp
  clang/lib/Interpreter/IncrementalParser.cpp
  clang/lib/Interpreter/Interpreter.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseTentative.cpp
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Serialization/ASTCommon.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/test/Interpreter/disambiguate-decl-stmt.cpp
  clang/test/Interpreter/execute-stmts.cpp
  clang/test/Interpreter/stmt-serialization.cpp
  clang/tools/libclang/CIndex.cpp
  clang/unittests/Interpreter/InterpreterTest.cpp

Index: clang/unittests/Interpreter/InterpreterTest.cpp
===
--- clang/unittests/Interpreter/InterpreterTest.cpp
+++ clang/unittests/Interpreter/InterpreterTest.cpp
@@ -124,14 +124,8 @@
   auto *PTU1 = R1->TUPart;
   EXPECT_EQ(2U, DeclsSize(PTU1));
 
-  // FIXME: Add support for wrapping and running statements.
   auto R2 = Interp->Parse("var1++; printf(\"var1 value %d\\n\", var1);");
-  EXPECT_FALSE(!!R2);
-  using ::testing::HasSubstr;
-  EXPECT_THAT(DiagnosticsOS.str(),
-  HasSubstr("error: unknown type name 'var1'"));
-  auto Err = R2.takeError();
-  EXPECT_EQ("Parsing failed.", llvm::toString(std::move(Err)));
+  EXPECT_TRUE(!!R2);
 }
 
 TEST(InterpreterTest, UndoCommand) {
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -6694,6 +6694,7 @@
   case Decl::Export:
   case Decl::ObjCPropertyImpl:
   case Decl::FileScopeAsm:
+  case Decl::TopLevelStmt:
   case Decl::StaticAssert:
   case Decl::Block:
   case Decl::Captured:
Index: clang/test/Interpreter/stmt-serialization.cpp
===
--- /dev/null
+++ clang/test/Interpreter/stmt-serialization.cpp
@@ -0,0 +1,19 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -std=c++20 -fincremental-extensions -fmodules-cache-path=%t \
+// RUN:-x c++ %s -verify
+// expected-no-diagnostics
+
+#pragma clang module build TopLevelStmt
+module TopLevelStmt { module Statements {} }
+#pragma clang module contents
+
+#pragma clang module begin TopLevelStmt.Statements
+extern "C" int printf(const char*,...);
+int i = 0;
+i++;
+#pragma clang module end /*TopLevelStmt.Statements*/
+#pragma clang module endbuild /*TopLevelStmt*/
+
+#pragma clang module import TopLevelStmt.Statements
+
+printf("Value of i is '%d'", i);
Index: clang/test/Interpreter/execute-stmts.cpp
===
--- /dev/null
+++ clang/test/Interpreter/execute-stmts.cpp
@@ -0,0 +1,38 @@
+// REQUIRES: host-supports-jit
+// UNSUPPORTED: system-aix
+// RUN: cat %s | clang-repl -Xcc -Xclang -Xcc  -verify | FileCheck %s
+// RUN: %clang_cc1 -verify -fincremental-extensions -emit-llvm -o -  %s \
+// RUN:   | FileCheck --check-prefix=CODEGEN-CHECK %s
+
+// expected-no-diagnostics
+
+//CODEGEN-CHECK-COUNT-2: define internal void @__stmts__
+//CODEGEN-CHECK-NOT: define internal void @__stmts__
+
+
+extern "C" int printf(const char*,...);
+
+template  T call() { printf("called\n"); return T(); }
+call();
+// CHECK: called
+
+int i = 1;
+++i;
+printf("i = %d\n", i);
+// CHECK: i = 2
+
+namespace Ns { void f(){ i++; } }
+Ns::f();
+
+void g() { ++i; }
+g();
+::g();
+
+printf("i = %d\n", i);
+// CHECK-NEXT: i = 5
+
+for (; i > 4; --i) printf("i = %d\n", i);
+// CHECK-NEXT: i = 5
+
+int j = i; printf("j = %d\n", j);
+// CHECK-NEXT: j = 4
Index: clang/test/Interpreter/disambiguate-decl-stmt.cpp
===
--- /dev/null
+++ clang/test/Interpreter/disambiguate-decl-stmt.cpp
@@ -0,0 +1,56 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -fincremental-extensions -std=c++20 %s
+// RUN: %clang_cc1 -fsyntax-only -DMS -fms-extensions -verify -fincremental-extensions -std=c++20 %s
+
+// expected-no-diagnostics
+
+extern 

[PATCH] D138939: [WIP][clang] adds a way to provide user-oriented reasons

2022-12-01 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

In D138939#3964439 , @erichkeane 
wrote:

> In D138939#3964404 , @cjdb wrote:
>
>> In D138939#3963496 , @erichkeane 
>> wrote:
>>
>>> In D138939#3963473 , @tschuett 
>>> wrote:
>>>
 Maybe `void FormatDiagnostic(SmallVectorImpl , DiagnosticMode 
 mode)`instead of `void FormatDiagnostic(SmallVectorImpl )`?
 To make the transition easer and future proof.
>>>
>>> I like this idea.  Perhaps with DiagnosticMode being a 3-way enum:
>>>
>>>   enum struct DiagnosticMode {
>>> Legacy,
>>> Sarif,  
>>> Default = Legacy
>>>   }
>>>
>>> I like the idea in particular, since it makes a command line flag to modify 
>>> "Default" to be whichever the user prefers pretty trivial.
>>
>> There's already a flag for this: `-fdiagnostics-format=sarif`. Why do we 
>> need a second diagnostic mode flag?
>
> Ah, oh... is the Sarif formatting being done with a new formatter?  That 
> seems unfortunate, since folks using the other formatters won't be able to 
> use the user friendly formats.

I've been alerted offline that I am misunderstanding the Sarif proposal, and 
where this is going.  I'll note that I wasn't present/invited at the calls 
where all of this was discussed, so I am admittedly not completely up to date.  
The above concern shouldn't stop others from reviewing this, particularly if 
you better understand the intent here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138939

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


[PATCH] D138296: [clang] Avoid duplicating ProgramAddressSpace in TargetInfo. NFCI

2022-12-01 Thread Alexander Richardson via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf3a17d059509: [clang] Avoid duplicating ProgramAddressSpace 
in TargetInfo. NFCI (authored by arichardson).

Changed prior to commit:
  https://reviews.llvm.org/D138296?vs=476473=479387#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138296

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/Basic/TargetInfo.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/Basic/Targets/AVR.h
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenTypes.cpp
  clang/lib/CodeGen/CodeGenTypes.h

Index: clang/lib/CodeGen/CodeGenTypes.h
===
--- clang/lib/CodeGen/CodeGenTypes.h
+++ clang/lib/CodeGen/CodeGenTypes.h
@@ -305,7 +305,7 @@
   bool isRecordBeingLaidOut(const Type *Ty) const {
 return RecordsBeingLaidOut.count(Ty);
   }
-
+  unsigned getTargetAddressSpace(QualType T) const;
 };
 
 }  // end namespace CodeGen
Index: clang/lib/CodeGen/CodeGenTypes.cpp
===
--- clang/lib/CodeGen/CodeGenTypes.cpp
+++ clang/lib/CodeGen/CodeGenTypes.cpp
@@ -655,7 +655,7 @@
 const ReferenceType *RTy = cast(Ty);
 QualType ETy = RTy->getPointeeType();
 llvm::Type *PointeeType = ConvertTypeForMem(ETy);
-unsigned AS = Context.getTargetAddressSpace(ETy);
+unsigned AS = getTargetAddressSpace(ETy);
 ResultType = llvm::PointerType::get(PointeeType, AS);
 break;
   }
@@ -665,7 +665,7 @@
 llvm::Type *PointeeType = ConvertTypeForMem(ETy);
 if (PointeeType->isVoidTy())
   PointeeType = llvm::Type::getInt8Ty(getLLVMContext());
-unsigned AS = Context.getTargetAddressSpace(ETy);
+unsigned AS = getTargetAddressSpace(ETy);
 ResultType = llvm::PointerType::get(PointeeType, AS);
 break;
   }
@@ -958,3 +958,13 @@
 bool CodeGenTypes::isZeroInitializable(const RecordDecl *RD) {
   return getCGRecordLayout(RD).isZeroInitializable();
 }
+
+unsigned CodeGenTypes::getTargetAddressSpace(QualType T) const {
+  // Return the address space for the type. If the type is a
+  // function type without an address space qualifier, the
+  // program address space is used. Otherwise, the target picks
+  // the best address space based on the type information
+  return T->isFunctionType() && !T.hasAddressSpace()
+ ? getDataLayout().getProgramAddressSpace()
+ : getContext().getTargetAddressSpace(T.getAddressSpace());
+}
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -3196,7 +3196,7 @@
   // See if there is already something with the target's name in the module.
   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
   if (Entry) {
-unsigned AS = getContext().getTargetAddressSpace(VD->getType());
+unsigned AS = getTypes().getTargetAddressSpace(VD->getType());
 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
 return ConstantAddress(Ptr, DeclTy, Alignment);
   }
@@ -3761,7 +3761,7 @@
   if (getTarget().supportsIFunc()) {
 ResolverType = llvm::FunctionType::get(
 llvm::PointerType::get(DeclTy,
-   Context.getTargetAddressSpace(FD->getType())),
+   getTypes().getTargetAddressSpace(FD->getType())),
 false);
   }
   else {
@@ -3899,8 +3899,8 @@
   // cpu_dispatch will be emitted in this translation unit.
   if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) {
 llvm::Type *ResolverType = llvm::FunctionType::get(
-llvm::PointerType::get(
-DeclTy, getContext().getTargetAddressSpace(FD->getType())),
+llvm::PointerType::get(DeclTy,
+   getTypes().getTargetAddressSpace(FD->getType())),
 false);
 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
 MangledName + ".resolver", ResolverType, GlobalDecl{},
Index: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -3133,7 +3133,7 @@
   const Type *NonQualTy = QC.strip(NativeParamType);
   QualType NativePointeeTy = cast(NonQualTy)->getPointeeType();
   unsigned NativePointeeAddrSpace =
-  CGF.getContext().getTargetAddressSpace(NativePointeeTy);
+  CGF.getTypes().getTargetAddressSpace(NativePointeeTy);
   QualType TargetTy = TargetParam->getType();
   llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
   LocalAddr, 

[clang] f3a17d0 - [clang] Avoid duplicating ProgramAddressSpace in TargetInfo. NFCI

2022-12-01 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2022-12-01T20:40:58Z
New Revision: f3a17d059509c133d8d90d305c0b40bdcbfc1fef

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

LOG: [clang] Avoid duplicating ProgramAddressSpace in TargetInfo. NFCI

This value was added to clang/Basic in D111566, but is only used during
codegen, where we can use the LLVM IR DataLayout instead. I noticed this
because the downstream CHERI targets would have to also set this value
for AArch64/RISC-V/MIPS. Instead of duplicating more information between
LLVM IR and Clang, this patch moves getTargetAddressSpace(QualType T) to
CodeGenTypes, where we can consult the DataLayout.

Reviewed By: rjmccall

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

Added: 


Modified: 
clang/include/clang/AST/ASTContext.h
clang/include/clang/Basic/TargetInfo.h
clang/lib/AST/ASTContext.cpp
clang/lib/Basic/TargetInfo.cpp
clang/lib/Basic/Targets/AVR.h
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGDebugInfo.cpp
clang/lib/CodeGen/CGDeclCXX.cpp
clang/lib/CodeGen/CGExpr.cpp
clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/CodeGenTypes.cpp
clang/lib/CodeGen/CodeGenTypes.h

Removed: 




diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 6f695f096857f..d7f538c136daf 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2810,8 +2810,6 @@ class ASTContext : public RefCountedBase {
   /// long double and double on AArch64 will return 0).
   int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const;
 
-  unsigned getTargetAddressSpace(QualType T) const;
-
   unsigned getTargetAddressSpace(LangAS AS) const;
 
   LangAS getLangASForBuiltinAddressSpace(unsigned AS) const;

diff  --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 38fd0f6405dfc..f010c559dc3e4 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -232,7 +232,6 @@ class TargetInfo : public virtual TransferrableTargetInfo,
   unsigned char RegParmMax, SSERegParmMax;
   TargetCXXABI TheCXXABI;
   const LangASMap *AddrSpaceMap;
-  unsigned ProgramAddrSpace;
 
   mutable StringRef PlatformName;
   mutable VersionTuple PlatformMinVersion;
@@ -822,9 +821,6 @@ class TargetInfo : public virtual TransferrableTargetInfo,
 return getTypeWidth(IntMaxType);
   }
 
-  /// Return the address space for functions for the given target.
-  unsigned getProgramAddressSpace() const { return ProgramAddrSpace; }
-
   // Return the size of unwind_word for this target.
   virtual unsigned getUnwindWordWidth() const {
 return getPointerWidth(LangAS::Default);

diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 464a386b09c3c..3c5d47fd964f3 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -12227,16 +12227,6 @@ uint64_t 
ASTContext::getTargetNullPointerValue(QualType QT) const {
   return getTargetInfo().getNullPointerValue(AS);
 }
 
-unsigned ASTContext::getTargetAddressSpace(QualType T) const {
-  // Return the address space for the type. If the type is a
-  // function type without an address space qualifier, the
-  // program address space is used. Otherwise, the target picks
-  // the best address space based on the type information
-  return T->isFunctionType() && !T.hasAddressSpace()
- ? getTargetInfo().getProgramAddressSpace()
- : getTargetAddressSpace(T.getAddressSpace());
-}
-
 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
   if (isTargetAddressSpace(AS))
 return toTargetAddressSpace(AS);

diff  --git a/clang/lib/Basic/TargetInfo.cpp b/clang/lib/Basic/TargetInfo.cpp
index 8def4be51016b..f735f58c7b8c2 100644
--- a/clang/lib/Basic/TargetInfo.cpp
+++ b/clang/lib/Basic/TargetInfo.cpp
@@ -155,8 +155,6 @@ TargetInfo::TargetInfo(const llvm::Triple ) : Triple(T) {
   MaxOpenCLWorkGroupSize = 1024;
 
   MaxBitIntWidth.reset();
-
-  ProgramAddrSpace = 0;
 }
 
 // Out of line virtual dtor for TargetInfo.

diff  --git a/clang/lib/Basic/Targets/AVR.h b/clang/lib/Basic/Targets/AVR.h
index 272afdfc03884..8b42144999751 100644
--- a/clang/lib/Basic/Targets/AVR.h
+++ b/clang/lib/Basic/Targets/AVR.h
@@ -55,7 +55,6 @@ class LLVM_LIBRARY_VISIBILITY AVRTargetInfo : public 
TargetInfo {
 Int16Type = SignedInt;
 Char32Type = UnsignedLong;
 SigAtomicType = SignedChar;
-ProgramAddrSpace = 1;
 resetDataLayout("e-P1-p:16:8-i8:8-i16:8-i32:8-i64:8-f32:8-f64:8-n8-a:8");
   }
 

diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index be788ad0d8687..0f410a8daae66 100644
--- 

[PATCH] D139137: add floor library function

2022-12-01 Thread Joshua Batista via Phabricator via cfe-commits
bob80905 created this revision.
bob80905 added reviewers: python3kgae, beanz.
Herald added a subscriber: Anastasia.
Herald added a project: All.
bob80905 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This change exposes the floor library function for HLSL,
excluding long, int, and long long doubles.
Floor is supported for all scalar, vector, and matrix types.

Long and long long double support is missing in this patch because those types
don't exist in HLSL. Int is missing because the floor function only works on 
floating type arguments.

The full documentation of the HLSL floor function is available here:
https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-floor


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D139137

Files:
  clang/lib/Headers/hlsl/hlsl_intrinsics.h
  clang/test/CodeGenHLSL/builtins/floor.hlsl

Index: clang/test/CodeGenHLSL/builtins/floor.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/builtins/floor.hlsl
@@ -0,0 +1,79 @@
+// RUN: %clang_cc1 -std=hlsl2021 -finclude-default-header -x hlsl -triple \
+// RUN:   dxil-pc-shadermodel6.3-library %s -fnative-half-type \
+// RUN:   -emit-llvm -disable-llvm-passes -O3 -o - | FileCheck %s
+// RUN: %clang_cc1 -std=hlsl2021 -finclude-default-header -x hlsl -triple \
+// RUN:   dxil-pc-shadermodel6.3-library %s -emit-llvm -disable-llvm-passes \
+// RUN:   -D__HLSL_ENABLE_16_BIT -o - | FileCheck %s --check-prefix=NO_HALF
+
+using hlsl::floor;
+
+// CHECK: define noundef half @
+// CHECK: call half @llvm.floor.f16(
+// NO_HALF: define noundef float @"?test_floor_half@@YA$halff@$halff@@Z"(
+// NO_HALF: call float @llvm.floor.f32(float %0)
+half test_floor_half ( half p0 ) {
+  return floor ( p0 );
+}
+// CHECK: define noundef <2 x half> @
+// CHECK: call <2 x half> @llvm.floor.v2f16(
+// NO_HALF: define noundef <2 x float> @"?test_floor_half2@@YAT?$__vector@$halff@$01@__clang@@T12@@Z"(
+// NO_HALF: call <2 x float> @llvm.floor.v2f32(
+half2 test_floor_half2 ( half2 p0 ) {
+  return floor ( p0 );
+}
+// CHECK: define noundef <3 x half> @
+// CHECK: call <3 x half> @llvm.floor.v3f16(
+// NO_HALF: define noundef <3 x float> @"?test_floor_half3@@YAT?$__vector@$halff@$02@__clang@@T12@@Z"(
+// NO_HALF: call <3 x float> @llvm.floor.v3f32(
+half3 test_floor_half3 ( half3 p0 ) {
+  return floor ( p0 );
+}
+// CHECK: define noundef <4 x half> @
+// CHECK: call <4 x half> @llvm.floor.v4f16(
+// NO_HALF: define noundef <4 x float> @"?test_floor_half4@@YAT?$__vector@$halff@$03@__clang@@T12@@Z"(
+// NO_HALF: call <4 x float> @llvm.floor.v4f32(
+half4 test_floor_half4 ( half4 p0 ) {
+  return floor ( p0 );
+}
+
+// CHECK: define noundef float @
+// CHECK: call float @llvm.floor.f32(
+float test_floor_float ( float p0 ) {
+  return floor ( p0 );
+}
+// CHECK: define noundef <2 x float> @
+// CHECK: call <2 x float> @llvm.floor.v2f32(
+float2 test_floor_float2 ( float2 p0 ) {
+  return floor ( p0 );
+}
+// CHECK: define noundef <3 x float> @
+// CHECK: call <3 x float> @llvm.floor.v3f32(
+float3 test_floor_float3 ( float3 p0 ) {
+  return floor ( p0 );
+}
+// CHECK: define noundef <4 x float> @
+// CHECK: call <4 x float> @llvm.floor.v4f32(
+float4 test_floor_float4 ( float4 p0 ) {
+  return floor ( p0 );
+}
+
+// CHECK: define noundef double @
+// CHECK: call double @llvm.floor.f64(
+double test_floor_double ( double p0 ) {
+  return floor ( p0 );
+}
+// CHECK: define noundef <2 x double> @
+// CHECK: call <2 x double> @llvm.floor.v2f64(
+double2 test_floor_double2 ( double2 p0 ) {
+  return floor ( p0 );
+}
+// CHECK: define noundef <3 x double> @
+// CHECK: call <3 x double> @llvm.floor.v3f64(
+double3 test_floor_double3 ( double3 p0 ) {
+  return floor ( p0 );
+}
+// CHECK: define noundef <4 x double> @
+// CHECK: call <4 x double> @llvm.floor.v4f64(
+double4 test_floor_double4 ( double4 p0 ) {
+  return floor ( p0 );
+}
Index: clang/lib/Headers/hlsl/hlsl_intrinsics.h
===
--- clang/lib/Headers/hlsl/hlsl_intrinsics.h
+++ clang/lib/Headers/hlsl/hlsl_intrinsics.h
@@ -101,6 +101,35 @@
 __attribute__((clang_builtin_alias(__builtin_elementwise_ceil)))
 double4 ceil(double4);
 
+// floor builtins
+#ifdef __HLSL_ENABLE_16_BIT
+__attribute__((clang_builtin_alias(__builtin_elementwise_floor))) half floor(half);
+__attribute__((clang_builtin_alias(__builtin_elementwise_floor)))
+half2 floor(half2);
+__attribute__((clang_builtin_alias(__builtin_elementwise_floor)))
+half3 floor(half3);
+__attribute__((clang_builtin_alias(__builtin_elementwise_floor)))
+half4 floor(half4);
+#endif
+
+__attribute__((clang_builtin_alias(__builtin_elementwise_floor))) float
+floor(float);
+__attribute__((clang_builtin_alias(__builtin_elementwise_floor)))
+float2 floor(float2);
+__attribute__((clang_builtin_alias(__builtin_elementwise_floor)))
+float3 floor(float3);

[PATCH] D139113: Fix a couple additional cases in misc-use-anonymous-namespace only

2022-12-01 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp marked 2 inline comments as done.
carlosgalvezp added inline comments.



Comment at: clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp:44
+  const SourceManager  = MatchedDecl->getASTContext().getSourceManager();
+  if (!SM.isWrittenInMainFile(MatchedDecl->getLocation()))
+return;

njames93 wrote:
> The logic would fall apart when run in clangd or unity builds. The safest way 
> is generally to match the file extension, we have a class for it in 
> `clang-tidy/utils`
Great suggestion, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139113

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


[PATCH] D139113: Fix a couple additional cases in misc-use-anonymous-namespace only

2022-12-01 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp updated this revision to Diff 479383.
carlosgalvezp added a comment.

Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139113

Files:
  clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp
  clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
  
clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
  clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp
@@ -1,4 +1,5 @@
-// RUN: %check_clang_tidy %s misc-use-anonymous-namespace %t
+// RUN: %check_clang_tidy %s misc-use-anonymous-namespace %t -- -header-filter=.* -- -I%S/Inputs
+#include "use-anonymous-namespace.h"
 
 static void f1();
 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: function 'f1' declared 'static', move to anonymous namespace instead [misc-use-anonymous-namespace]
@@ -57,3 +58,7 @@
 {
   static int x;
 }
+
+// OK
+static const int v8{123};
+static constexpr int v9{123};
Index: clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h
@@ -0,0 +1,3 @@
+// Should not warn here, do not require anonymous namespaces in headers
+static int gv{123};
+static void gf(){}
Index: clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
===
--- clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
+++ clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_USEANONYMOUSNAMESPACECHECK_H
 
 #include "../ClangTidyCheck.h"
+#include "../utils/FileExtensionsUtils.h"
 
 namespace clang {
 namespace tidy {
@@ -23,8 +24,7 @@
 /// http://clang.llvm.org/extra/clang-tidy/checks/modernize/use-anonymous-namespace.html
 class UseAnonymousNamespaceCheck : public ClangTidyCheck {
 public:
-  UseAnonymousNamespaceCheck(StringRef Name, ClangTidyContext *Context)
-  : ClangTidyCheck(Name, Context) {}
+  UseAnonymousNamespaceCheck(StringRef Name, ClangTidyContext *Context);
   bool isLanguageVersionSupported(const LangOptions ) const override {
 return LangOpts.CPlusPlus;
   }
@@ -32,6 +32,7 @@
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
 
 private:
+  utils::FileExtensionsSet HeaderFileExtensions;
   template  void processMatch(const T *MatchedDecl);
 };
 
Index: clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp
===
--- clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp
+++ clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp
@@ -37,16 +37,32 @@
   return false;
 }
 
+UseAnonymousNamespaceCheck::UseAnonymousNamespaceCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context) {
+  if (!utils::parseFileExtensions(utils::defaultHeaderFileExtensions(),
+  HeaderFileExtensions,
+  utils::defaultFileExtensionDelimiters())) {
+this->configurationDiag("Invalid header file extension: '%0'")
+<< utils::defaultHeaderFileExtensions();
+  }
+}
+
 template 
 void UseAnonymousNamespaceCheck::processMatch(const T *MatchedDecl) {
+  // Enforce anonymous namespaces only in source files, not headers
+  SourceLocation Loc = MatchedDecl->getLocation();
+  SourceManager  = MatchedDecl->getASTContext().getSourceManager();
+  if (utils::isSpellingLocInHeaderFile(Loc, SM, HeaderFileExtensions))
+return;
+
   StringRef Type = llvm::isa(MatchedDecl) ? "variable" : "function";
   if (isInAnonymousNamespace(MatchedDecl))
-diag(MatchedDecl->getLocation(), "%0 %1 declared 'static' in "
- "anonymous namespace, remove 'static'")
+diag(Loc, "%0 %1 declared 'static' in "
+  "anonymous namespace, remove 'static'")
 << Type << MatchedDecl;
   else
-diag(MatchedDecl->getLocation(),
- "%0 %1 declared 'static', move to anonymous namespace instead")
+diag(Loc, "%0 %1 declared 'static', move to anonymous namespace instead")
 << Type << MatchedDecl;
 }
 
@@ -54,7 +70,8 @@
   Finder->addMatcher(
   functionDecl(isStatic(), unless(isMemberFunction())).bind("func"), this);
   Finder->addMatcher(
-  varDecl(isStatic(), unless(anyOf(isStaticLocal(), isStaticDataMember(
+  varDecl(isStatic(), unless(anyOf(isStaticLocal(), isStaticDataMember(),
+

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

2022-12-01 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 added inline comments.



Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:54-55
+  bool TraverseDecl(Decl *Node) {
+if (!Node)
+  return true;
+if (!match(*Node))

NoQ wrote:
> ziqingluo-90 wrote:
> > steakhal wrote:
> > > Can `Node` be ever null if the visitor is initiated only be 
> > > `AST_MATCHER_P`?
> > Honestly I do not know the exact answer to your question.  I was imagining 
> > that an AST node could have a null to be one of its children.
> > 
> > Our plan later is to make this matcher a general alternative to 
> > `forEachDescendant`, so I think the check for null here is not 
> > over-defensive.
> There can definitely be null children in the AST. Eg. `for(;;) {}` has null 
> initializer, null condition, null increment, non-null body. I guess this is 
> more about whether `RecursiveASTVisitor` checks for that automatically before 
> invoking callbacks.
>  I guess this is more about whether RecursiveASTVisitor checks for that 
> automatically before invoking callbacks.

The override-ed `TraverseDecl` method in the base class `RecursiveASTVisitor` 
also has a null-check. So I feel like this null-check is needed here.



Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:59
+// To skip callables:
+if (llvm::isa(Node))
+  return true;

NoQ wrote:
> `llvm::` is unnecessary, we're under `using namespace llvm`.




Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:71
+// To skip callables:
+if (llvm::isa(Node))
+  return true;




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138329

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


[PATCH] D138318: [-Wunsafe-buffer-usage] Improve pointer match pattern

2022-12-01 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 added inline comments.



Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:30-39
+  return anyOf(
+hasType(pointerType()),
+hasType(autoType(
+hasDeducedType(hasUnqualifiedDesugaredType(pointerType(),
+// DecayedType, e.g., array type in formal parameter decl
+hasType(decayedType(hasDecayedType(pointerType(,
+// ElaboratedType, e.g., typedef





Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:31
+  return anyOf(
+hasType(pointerType()),
+hasType(autoType(

aaron.ballman wrote:
> I shudder to ask this question, but ... pointer to member types?
My understanding is that a pointer-to-member type pointer cannot be used to do 
buffer access, i.e., one cannot do pointer addition on it.  So we do not warn 
pointer-to-member themselves.  In cases where the member type is a pointer, it 
has been covered.  

I have added a test involving pointer to member types.



Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:35
+// DecayedType, e.g., array type in formal parameter decl
+hasType(decayedType(hasDecayedType(pointerType(,
+// ElaboratedType, e.g., typedef

aaron.ballman wrote:
> hmmm, do you need to check `hasDecayedType(pointerType())`? What decay type 
> *isn't* a pointer type?
you are right! Thanks for pointing this out.



Comment at: clang/test/SemaCXX/warn-unsafe-buffer-usage.cpp:164
+}
+
+#endif




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

https://reviews.llvm.org/D138318

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


[PATCH] D139113: Fix a couple additional cases in misc-use-anonymous-namespace only

2022-12-01 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp:44
+  const SourceManager  = MatchedDecl->getASTContext().getSourceManager();
+  if (!SM.isWrittenInMainFile(MatchedDecl->getLocation()))
+return;

The logic would fall apart when run in clangd or unity builds. The safest way 
is generally to match the file extension, we have a class for it in 
`clang-tidy/utils`



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp:51
 struct Foo {
-  static void f();
-  static int x;

These changes just look like noise.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139113

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


[PATCH] D137107: Allow MS extension: support of constexpr with __declspec(dllimport).

2022-12-01 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a reviewer: aeubanks.
efriedma added a subscriber: aeubanks.
efriedma added a comment.

I'm not really familiar with the way constructor priorities work on Windows 
works... see https://reviews.llvm.org/D131910 ?  Adding @aeubanks as a reviewer.


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

https://reviews.llvm.org/D137107

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


[PATCH] D137379: [-Wunsafe-buffer-usage] Add warnings for unsafe buffer accesses by array subscript operations

2022-12-01 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 added inline comments.



Comment at: clang/test/SemaCXX/warn-unsafe-buffer-usage.cpp:10-13
+void foo(...);
+
+void * bar(void);
+char * baz(void);

jkorous wrote:
> NoQ wrote:
> > ziqingluo-90 wrote:
> > > steakhal wrote:
> > > > NoQ wrote:
> > > > > ziqingluo-90 wrote:
> > > > > > steakhal wrote:
> > > > > > > I would expect this test file to grow quite a bit.
> > > > > > > As such, I think we should have more self-descriptive names for 
> > > > > > > these functions.
> > > > > > > 
> > > > > > > I'm also curious what's the purpose of `foo()`in the examples.
> > > > > > Thanks for the comment.  I agree that they should have better names 
> > > > > > or at least explaining comments.
> > > > > > 
> > > > > > > I'm also curious what's the purpose of `foo()`in the examples.
> > > > > > 
> > > > > > I make all testing expressions arguments of `foo` so that I do not 
> > > > > > have to create statements to use these expressions while avoiding 
> > > > > > irrelevant warnings.
> > > > > That's pretty cool but please note that when `foo()` is declared this 
> > > > > way, it becomes a "C-style variadic function" - a very exotic 
> > > > > construct that you don't normally see in code (the only practical 
> > > > > example is the `printf`/`scanf` family of functions). So it may be 
> > > > > good that we cover this exotic case from the start, but it may also 
> > > > > be really bad that we don't cover the *basic* case.
> > > > > 
> > > > > C++ offers a different way to declare variadic functions: //variadic 
> > > > > templates// 
> > > > > (https://en.cppreference.com/w/cpp/language/parameter_pack). These 
> > > > > are less valuable to test because they expand to AST that's very 
> > > > > similar to the basic case, but that also allows you to cover the 
> > > > > basic case better.
> > > > > 
> > > > > Or you can always make yourself happy with a few overloads that cover 
> > > > > all your needs, it's not like we're worried about code duplication in 
> > > > > tests:
> > > > > ```lang=c++
> > > > > void foo(int);
> > > > > void foo(int, int);
> > > > > void foo(int, int, int);
> > > > > void foo(int, int, int, int);
> > > > > void foo(int, int, int, int, int);
> > > > > void foo(int, int, int, int, int, int);
> > > > > ```
> > > > IMO its fine. I would probably call it `sink()` though. Ive used the 
> > > > same construct for the same reason in CSA tests with this name.
> > > I don't quite get what "basic case" refers to.  Could you explain it to 
> > > me a little more?
> > By "basic case" I mean the ordinary, non-variadic function call with 
> > predefined set of arguments in the prototype.
> @ziqingluo-90 If the only purpose of `foo()` is to suppress warnings about 
> unused values then you might also consider just suppressing those warnings 
> with relevant `-Wno...` flags.
I now see that using a C variadic function could bring some unexpected 
behaviors such as implicit casts from lvalue reference to rvalue.   There are 
following patches whose tests also use `foo`.  I plan to add an NFC patch later 
to remove all uses of `foo`, if this sounds ok. 


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

https://reviews.llvm.org/D137379

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


[PATCH] D138939: [WIP][clang] adds a way to provide user-oriented reasons

2022-12-01 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

In D138939#3964404 , @cjdb wrote:

> In D138939#3963496 , @erichkeane 
> wrote:
>
>> In D138939#3963473 , @tschuett 
>> wrote:
>>
>>> Maybe `void FormatDiagnostic(SmallVectorImpl , DiagnosticMode 
>>> mode)`instead of `void FormatDiagnostic(SmallVectorImpl )`?
>>> To make the transition easer and future proof.
>>
>> I like this idea.  Perhaps with DiagnosticMode being a 3-way enum:
>>
>>   enum struct DiagnosticMode {
>> Legacy,
>> Sarif,  
>> Default = Legacy
>>   }
>>
>> I like the idea in particular, since it makes a command line flag to modify 
>> "Default" to be whichever the user prefers pretty trivial.
>
> There's already a flag for this: `-fdiagnostics-format=sarif`. Why do we need 
> a second diagnostic mode flag?

Ah, oh... is the Sarif formatting being done with a new formatter?  That seems 
unfortunate, since folks using the other formatters won't be able to use the 
user friendly formats.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138939

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


[PATCH] D131939: [clang-tidy] Add performance-expensive-flat-container-operation check

2022-12-01 Thread Nicolas van Kempen via Phabricator via cfe-commits
nicovank marked an inline comment as done.
nicovank added a comment.

Ping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131939

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


[PATCH] D138939: [WIP][clang] adds a way to provide user-oriented reasons

2022-12-01 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb marked 3 inline comments as done.
cjdb added a comment.

In D138939#3963496 , @erichkeane 
wrote:

> In D138939#3963473 , @tschuett 
> wrote:
>
>> Maybe `void FormatDiagnostic(SmallVectorImpl , DiagnosticMode 
>> mode)`instead of `void FormatDiagnostic(SmallVectorImpl )`?
>> To make the transition easer and future proof.
>
> I like this idea.  Perhaps with DiagnosticMode being a 3-way enum:
>
>   enum struct DiagnosticMode {
> Legacy,
> Sarif,  
> Default = Legacy
>   }
>
> I like the idea in particular, since it makes a command line flag to modify 
> "Default" to be whichever the user prefers pretty trivial.

There's already a flag for this: `-fdiagnostics-format=sarif`. Why do we need a 
second diagnostic mode flag?




Comment at: clang/tools/clang-format/ClangFormat.cpp:397
+  Info.FormatSummary(vec);
+  Info.FormatLegacyReason(vec);
 errs() << "clang-format error:" << vec << "\n";

rymiel wrote:
> I don't think this indent change was intended?
I find it ironic that clang-format misformatted ClangFormat.cpp.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138939

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


[PATCH] D139045: [HIP] use detected GPU in --offload-arch

2022-12-01 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 479365.
yaxunl added a comment.

fix error handling


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

https://reviews.llvm.org/D139045

Files:
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/AMDGPU.h


Index: clang/lib/Driver/ToolChains/AMDGPU.h
===
--- clang/lib/Driver/ToolChains/AMDGPU.h
+++ clang/lib/Driver/ToolChains/AMDGPU.h
@@ -118,6 +118,9 @@
   llvm::Error getSystemGPUArch(const llvm::opt::ArgList ,
std::string ) const;
 
+  llvm::Error detectSystemGPUs(const llvm::opt::ArgList ,
+   SmallVector ) const;
+
 protected:
   /// Check and diagnose invalid target ID specified by -mcpu.
   virtual void checkTargetID(const llvm::opt::ArgList ) const;
@@ -137,8 +140,6 @@
   /// Get GPU arch from -mcpu without checking.
   StringRef getGPUArch(const llvm::opt::ArgList ) const;
 
-  llvm::Error detectSystemGPUs(const llvm::opt::ArgList ,
-   SmallVector ) const;
 };
 
 class LLVM_LIBRARY_VISIBILITY ROCMToolChain : public AMDGPUToolChain {
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -3312,13 +3312,25 @@
   for (auto Arch : GpuArchs)
 GpuArchList.push_back(Arch.data());
 
-  // Default to sm_20 which is the lowest common denominator for
+  // CUDA defaults to sm_20 which is the lowest common denominator for
   // supported GPUs.  sm_20 code should work correctly, if
   // suboptimally, on all newer GPUs.
   if (GpuArchList.empty()) {
 if (ToolChains.front()->getTriple().isSPIRV())
   GpuArchList.push_back(CudaArch::Generic);
-else
+else if (ToolChains.front()->getTriple().isAMDGPU()) {
+  auto *TC = static_cast(
+  ToolChains.front());
+  SmallVector GPUs;
+  auto Err = TC->detectSystemGPUs(Args, GPUs);
+  if (!Err) {
+for (auto GPU : GPUs)
+  GpuArchList.push_back(Args.MakeArgString(GPU));
+  } else {
+llvm::consumeError(std::move(Err));
+GpuArchList.push_back(DefaultCudaArch);
+  }
+} else
   GpuArchList.push_back(DefaultCudaArch);
   }
 


Index: clang/lib/Driver/ToolChains/AMDGPU.h
===
--- clang/lib/Driver/ToolChains/AMDGPU.h
+++ clang/lib/Driver/ToolChains/AMDGPU.h
@@ -118,6 +118,9 @@
   llvm::Error getSystemGPUArch(const llvm::opt::ArgList ,
std::string ) const;
 
+  llvm::Error detectSystemGPUs(const llvm::opt::ArgList ,
+   SmallVector ) const;
+
 protected:
   /// Check and diagnose invalid target ID specified by -mcpu.
   virtual void checkTargetID(const llvm::opt::ArgList ) const;
@@ -137,8 +140,6 @@
   /// Get GPU arch from -mcpu without checking.
   StringRef getGPUArch(const llvm::opt::ArgList ) const;
 
-  llvm::Error detectSystemGPUs(const llvm::opt::ArgList ,
-   SmallVector ) const;
 };
 
 class LLVM_LIBRARY_VISIBILITY ROCMToolChain : public AMDGPUToolChain {
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -3312,13 +3312,25 @@
   for (auto Arch : GpuArchs)
 GpuArchList.push_back(Arch.data());
 
-  // Default to sm_20 which is the lowest common denominator for
+  // CUDA defaults to sm_20 which is the lowest common denominator for
   // supported GPUs.  sm_20 code should work correctly, if
   // suboptimally, on all newer GPUs.
   if (GpuArchList.empty()) {
 if (ToolChains.front()->getTriple().isSPIRV())
   GpuArchList.push_back(CudaArch::Generic);
-else
+else if (ToolChains.front()->getTriple().isAMDGPU()) {
+  auto *TC = static_cast(
+  ToolChains.front());
+  SmallVector GPUs;
+  auto Err = TC->detectSystemGPUs(Args, GPUs);
+  if (!Err) {
+for (auto GPU : GPUs)
+  GpuArchList.push_back(Args.MakeArgString(GPU));
+  } else {
+llvm::consumeError(std::move(Err));
+GpuArchList.push_back(DefaultCudaArch);
+  }
+} else
   GpuArchList.push_back(DefaultCudaArch);
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D138393: HIP: Directly call fabs builtins

2022-12-01 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

ping


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

https://reviews.llvm.org/D138393

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


[PATCH] D128958: Add assembler plumbing for sanitize_memtag

2022-12-01 Thread Mitch Phillips 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 rG850defb86164: Add assembler plumbing for sanitize_memtag 
(authored by hctim).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128958

Files:
  clang/test/Driver/memtag-stack.c
  clang/test/Driver/memtag-stack_lto.c
  clang/test/Driver/memtag_lto.c
  llvm/include/llvm/BinaryFormat/ELF.h
  llvm/include/llvm/MC/MCAsmInfo.h
  llvm/include/llvm/MC/MCDirectives.h
  llvm/include/llvm/MC/MCELFObjectWriter.h
  llvm/include/llvm/MC/MCSymbolELF.h
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/MC/ELFObjectWriter.cpp
  llvm/lib/MC/MCAsmStreamer.cpp
  llvm/lib/MC/MCELFStreamer.cpp
  llvm/lib/MC/MCMachOStreamer.cpp
  llvm/lib/MC/MCParser/AsmParser.cpp
  llvm/lib/MC/MCSymbolELF.cpp
  llvm/lib/Target/AArch64/MCTargetDesc/AArch64ELFObjectWriter.cpp
  llvm/test/MC/AArch64/global-tagging.ll

Index: llvm/test/MC/AArch64/global-tagging.ll
===
--- /dev/null
+++ llvm/test/MC/AArch64/global-tagging.ll
@@ -0,0 +1,46 @@
+;; Tagged symbols are only available on aarch64-linux-android.
+; RUN: not llc %s -mtriple=aarch64-linux-unknown
+; RUN: not llc %s -mtriple=x86_64-linux-unknown
+
+; RUN: llc %s -mtriple=aarch64-linux-android31 -o %t.S
+; RUN: FileCheck %s --input-file=%t.S --check-prefix=CHECK-ASM
+; RUN: llvm-mc -filetype=obj %t.S -triple=aarch64-linux-android31 -o %t.o
+; RUN: llvm-readelf -r %t.o | FileCheck %s --check-prefix=CHECK-RELOCS
+
+; RUN: obj2yaml %t.o -o %t.yaml
+; RUN: FileCheck %s --input-file=%t.yaml --check-prefix=CHECK-YAML
+; RUN: yaml2obj %t.yaml -o %t.o
+; RUN: llvm-readelf -r %t.o | FileCheck %s --check-prefix=CHECK-RELOCS
+
+; CHECK-RELOCS: Relocation section '.rela.memtag.globals.static' {{.*}} contains 4 entries
+; CHECK-RELOCS: R_AARCH64_NONE {{.*}} internal_four
+; CHECK-RELOCS: R_AARCH64_NONE {{.*}} four
+; CHECK-RELOCS: R_AARCH64_NONE {{.*}} sixteen
+; CHECK-RELOCS: R_AARCH64_NONE {{.*}} huge
+; CHECK-RELOCS-NOT: specialcaselisted
+
+; CHECK-YAML:  Sections:
+; CHECK-YAML:  - Name: .rela.memtag.globals.static
+; CHECK-YAML-NOT:  - Name:
+; CHECK-YAML:  Relocations:
+; CHECK-YAML-NEXT: - Symbol: internal_four
+; CHECK-YAML-NEXT: Type: R_AARCH64_NONE
+; CHECK-YAML-NEXT: - Symbol: four
+; CHECK-YAML-NEXT: Type: R_AARCH64_NONE
+; CHECK-YAML-NEXT: - Symbol: sixteen
+; CHECK-YAML-NEXT: Type: R_AARCH64_NONE
+; CHECK-YAML-NEXT: - Symbol: huge
+; CHECK-YAML-NEXT: Type: R_AARCH64_NONE
+; CHECK-YAML-NEXT: -
+
+; CHECK-ASM: .memtag internal_four
+; CHECK-ASM: .memtag four
+; CHECK-ASM: .memtag sixteen
+; CHECK-ASM: .memtag huge
+; CHECK-ASM-NOT: .memtag specialcaselisted
+
+@internal_four = internal global i32 1, sanitize_memtag
+@four = global i32 1, sanitize_memtag
+@sixteen = global [16 x i8] zeroinitializer, sanitize_memtag
+@huge = global [16777232 x i8] zeroinitializer, sanitize_memtag
+@specialcaselisted = global i16 2
Index: llvm/lib/Target/AArch64/MCTargetDesc/AArch64ELFObjectWriter.cpp
===
--- llvm/lib/Target/AArch64/MCTargetDesc/AArch64ELFObjectWriter.cpp
+++ llvm/lib/Target/AArch64/MCTargetDesc/AArch64ELFObjectWriter.cpp
@@ -34,6 +34,8 @@
 
   ~AArch64ELFObjectWriter() override = default;
 
+  MCSectionELF *getMemtagRelocsSection(MCContext ) const override;
+
 protected:
   unsigned getRelocType(MCContext , const MCValue ,
 const MCFixup , bool IsPCRel) const override;
@@ -453,6 +455,12 @@
   llvm_unreachable("Unimplemented fixup -> relocation");
 }
 
+MCSectionELF *
+AArch64ELFObjectWriter::getMemtagRelocsSection(MCContext ) const {
+  return Ctx.getELFSection(".memtag.globals.static",
+   ELF::SHT_AARCH64_MEMTAG_GLOBALS_STATIC, 0);
+}
+
 std::unique_ptr
 llvm::createAArch64ELFObjectWriter(uint8_t OSABI, bool IsILP32) {
   return std::make_unique(OSABI, IsILP32);
Index: llvm/lib/MC/MCSymbolELF.cpp
===
--- llvm/lib/MC/MCSymbolELF.cpp
+++ llvm/lib/MC/MCSymbolELF.cpp
@@ -33,7 +33,10 @@
   ELF_WeakrefUsedInReloc_Shift = 11,
 
   // One bit.
-  ELF_BindingSet_Shift = 12
+  ELF_BindingSet_Shift = 12,
+
+  // One bit.
+  ELF_IsMemoryTagged_Shift = 13,
 };
 }
 
@@ -193,4 +196,16 @@
 bool MCSymbolELF::isBindingSet() const {
   return getFlags() & (0x1 << ELF_BindingSet_Shift);
 }
+
+bool MCSymbolELF::isMemtag() const {
+  return getFlags() & (0x1 << ELF_IsMemoryTagged_Shift);
+}
+
+void MCSymbolELF::setMemtag(bool Tagged) {
+  uint32_t OtherFlags = getFlags() & ~(1 << ELF_IsMemoryTagged_Shift);
+  if (Tagged)
+setFlags(OtherFlags | (1 << ELF_IsMemoryTagged_Shift));
+  else
+setFlags(OtherFlags);
+}
 }
Index: llvm/lib/MC/MCParser/AsmParser.cpp

[clang] 850defb - Add assembler plumbing for sanitize_memtag

2022-12-01 Thread Mitch Phillips via cfe-commits

Author: Mitch Phillips
Date: 2022-12-01T10:50:34-08:00
New Revision: 850defb86164f1a68816b21f31529d871400a454

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

LOG: Add assembler plumbing for sanitize_memtag

Extends the Asm reader/writer to support reading and writing the
'.memtag' directive (including allowing it on internal global
variables). Also add some extra tooling support, including objdump and
yaml2obj/obj2yaml.

Test that the sanitize_memtag IR attribute produces the expected asm
directive.

Uses the new Aarch64 MemtagABI specification
(https://github.com/ARM-software/abi-aa/blob/main/memtagabielf64/memtagabielf64.rst)
to identify symbols as tagged in object files. This is done using a
R_AARCH64_NONE relocation that identifies each tagged symbol, and these
relocations are tagged in a special SHT_AARCH64_MEMTAG_GLOBALS_STATIC
section. This signals to the linker that the global variable should be
tagged.

Reviewed By: fmayer, MaskRay, peter.smith

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

Added: 
clang/test/Driver/memtag-stack_lto.c
llvm/test/MC/AArch64/global-tagging.ll

Modified: 
clang/test/Driver/memtag-stack.c
llvm/include/llvm/BinaryFormat/ELF.h
llvm/include/llvm/MC/MCAsmInfo.h
llvm/include/llvm/MC/MCDirectives.h
llvm/include/llvm/MC/MCELFObjectWriter.h
llvm/include/llvm/MC/MCSymbolELF.h
llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
llvm/lib/MC/ELFObjectWriter.cpp
llvm/lib/MC/MCAsmStreamer.cpp
llvm/lib/MC/MCELFStreamer.cpp
llvm/lib/MC/MCMachOStreamer.cpp
llvm/lib/MC/MCParser/AsmParser.cpp
llvm/lib/MC/MCSymbolELF.cpp
llvm/lib/Target/AArch64/MCTargetDesc/AArch64ELFObjectWriter.cpp

Removed: 
clang/test/Driver/memtag_lto.c



diff  --git a/clang/test/Driver/memtag-stack.c 
b/clang/test/Driver/memtag-stack.c
index 9f22f6687f86..58003fd1b02b 100644
--- a/clang/test/Driver/memtag-stack.c
+++ b/clang/test/Driver/memtag-stack.c
@@ -1,7 +1,7 @@
-// RUN: %clang -target aarch64-unknown-linux -march=armv8+memtag 
-fsanitize=memtag -mllvm -stack-safety-print=1 %s -S -o - 2>&1 | FileCheck %s 
--check-prefix=CHECK-NO-SAFETY
-// RUN: %clang -O1 -target aarch64-unknown-linux -march=armv8+memtag 
-fsanitize=memtag -mllvm -stack-safety-print=1 %s -S -o - 2>&1 | FileCheck %s 
--check-prefix=CHECK-SAFETY
-// RUN: %clang -O2 -target aarch64-unknown-linux -march=armv8+memtag 
-fsanitize=memtag -mllvm -stack-safety-print=1 %s -S -o - 2>&1 | FileCheck %s 
--check-prefix=CHECK-SAFETY
-// RUN: %clang -O3 -target aarch64-unknown-linux -march=armv8+memtag 
-fsanitize=memtag -mllvm -stack-safety-print=1 %s -S -o - 2>&1 | FileCheck %s 
--check-prefix=CHECK-SAFETY
+// RUN: %clang -target aarch64-unknown-linux -march=armv8+memtag 
-fsanitize=memtag-stack -mllvm -stack-safety-print=1 %s -S -o - 2>&1 | 
FileCheck %s --check-prefix=CHECK-NO-SAFETY
+// RUN: %clang -O1 -target aarch64-unknown-linux -march=armv8+memtag 
-fsanitize=memtag-stack -mllvm -stack-safety-print=1 %s -S -o - 2>&1 | 
FileCheck %s --check-prefix=CHECK-SAFETY
+// RUN: %clang -O2 -target aarch64-unknown-linux -march=armv8+memtag 
-fsanitize=memtag-stack -mllvm -stack-safety-print=1 %s -S -o - 2>&1 | 
FileCheck %s --check-prefix=CHECK-SAFETY
+// RUN: %clang -O3 -target aarch64-unknown-linux -march=armv8+memtag 
-fsanitize=memtag-stack -mllvm -stack-safety-print=1 %s -S -o - 2>&1 | 
FileCheck %s --check-prefix=CHECK-SAFETY
 
 // REQUIRES: aarch64-registered-target
 

diff  --git a/clang/test/Driver/memtag_lto.c 
b/clang/test/Driver/memtag-stack_lto.c
similarity index 85%
rename from clang/test/Driver/memtag_lto.c
rename to clang/test/Driver/memtag-stack_lto.c
index 2ad22141608c..2fe15a119d2a 100644
--- a/clang/test/Driver/memtag_lto.c
+++ b/clang/test/Driver/memtag-stack_lto.c
@@ -33,14 +33,14 @@
 // RUN: rm -f %t*
 
 // -O0: both are unsafe.
-// RUN: %clang -O0 -target aarch64-unknown-linux -march=armv8+memtag 
-fsanitize=memtag -mllvm -stack-safety-print %s -S -o - 2>&1 | FileCheck %s
+// RUN: %clang -O0 -target aarch64-unknown-linux -march=armv8+memtag 
-fsanitize=memtag-stack -mllvm -stack-safety-print %s -S -o - 2>&1 | FileCheck 
%s
 
 // No LTO: just one is safe.
-// RUN: %clang -O1 -target aarch64-unknown-linux -march=armv8+memtag 
-fsanitize=memtag -mllvm -stack-safety-print %s -S -o /dev/null 2>&1 | 
FileCheck %s -check-prefixes=SSI,XUNSAFE,YSAFE
+// RUN: %clang -O1 -target aarch64-unknown-linux -march=armv8+memtag 
-fsanitize=memtag-stack -mllvm -stack-safety-print %s -S -o /dev/null 2>&1 | 
FileCheck %s -check-prefixes=SSI,XUNSAFE,YSAFE
 
 // Full LTO: both are safe.
-// RUN: %clang -O1 -target aarch64-unknown-linux -march=armv8+memtag 
-fsanitize=memtag -c %s -Xclang -opaque-pointers -flto=full -o %t.ltonewpm1.bc
-// RUN: %clang -O1 -target 

[PATCH] D138651: [CUDA][HIP] Don't diagnose use for __bf16

2022-12-01 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: clang/test/SemaCUDA/amdgpu-bf16.cu:9
+
+__device__ void devicefn() {
+}

Pierre-vh wrote:
> tra wrote:
> > We should probably also have a case verifying that actual attempt to use 
> > `__bf16` in device code is still diagnosed. 
> Good catch, it's currently no longer diagnosed.
> What can I use in `ConvertDeclSpecToType` to make it diagnose only if the 
> current function is a device function? If I understand correctly, LangOpts 
> are for the whole TU so I can't use that (e.g. CUDAIsDevice), right?
I don't have a good answer. That was one of the reasons I ended up implementing 
`__bf16` support in NVPTX. :-)
You may need to use deferred diagnostics, instead of disabling them) and 
trigger them if we need to codegen anything that uses `__bf16`.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138651

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


[PATCH] D139023: [NFC][Clang][Driver][AMDGPU] Avoid temporary copies of std::string by using Twine and StringRef

2022-12-01 Thread Artem Belevich via Phabricator via cfe-commits
tra accepted this revision.
tra added a comment.
This revision is now accepted and ready to land.

LGTM in principle.

That said, I don't think `StringRef `buys us anything here as none of this code 
is in the hot path. It also comes with the downside that now one has to worry 
about lifetimes of the strings we refer to. Things do look OK in this case, but 
it would be good if it could be confirmed with sanitizer. 
In code that's not performance critical I personally prefer passing std::string 
by value and let compiler optimize them away.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139023

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


[PATCH] D138296: [clang] Avoid duplicating ProgramAddressSpace in TargetInfo. NFCI

2022-12-01 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

I think this is fine.  Most of the patch is changing calls to 
`getTargetAddressSpace` to be internal to IRGen, which, as mentioned, I think 
is the right move.

I do think that if we're going to support multiple program address spaces 
(which seems to be a goal) that we'll eventually want an AST-level concept of 
the default program address space, but perpetuating the use of target ASes at 
the AST level isn't the right way to approach that, so this is still the right 
first step.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138296

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


[PATCH] D139073: [X86] AMD Zen 4 Initial enablement

2022-12-01 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added a comment.

Thank you @gganesh I thought you'd forgotten about us :)

Please add znver4 test coverage to:

llvm/test/CodeGen/X86/cpus-amd.ll
llvm/test/CodeGen/X86/slow-unaligned-mem.ll




Comment at: llvm/lib/Target/X86/X86.td:1619
 ProcessorFeatures.ZN3Tuning>;
+def : ProcModel<"znver4", Znver3Model, ProcessorFeatures.ZN4Features,
+ProcessorFeatures.ZN4Tuning>;

This might sound strange - but its probably better to use either the IceLake or 
SkylakeServer model initially - as they have AVX512 instruction coverage, the 
znver3 model will assert in llvm-mca etc when it encounters an unsupported 
instruction (any of the Z sched classes).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139073

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


[PATCH] D138822: [clang] Add test for CWG36

2022-12-01 Thread Vlad Serebrennikov 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 rGf5993fc7757e: [clang] Add test for CWG36 (authored by 
Endill).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138822

Files:
  clang/test/CXX/drs/dr0xx.cpp
  clang/www/cxx_dr_status.html

Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -254,7 +254,7 @@
 https://wg21.link/cwg36;>36
 CD6
 using-declarations in multiple-declaration contexts
-Unknown
+Yes
   
   
 https://wg21.link/cwg37;>37
Index: clang/test/CXX/drs/dr0xx.cpp
===
--- clang/test/CXX/drs/dr0xx.cpp
+++ clang/test/CXX/drs/dr0xx.cpp
@@ -2,6 +2,8 @@
 // RUN: %clang_cc1 -std=c++11 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple
 // RUN: %clang_cc1 -std=c++14 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple
 // RUN: %clang_cc1 -std=c++17 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple
+// RUN: %clang_cc1 -std=c++20 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple
+// RUN: %clang_cc1 -std=c++2b %s -verify -fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple
 
 namespace dr1 { // dr1: no
   namespace X { extern "C" void dr1_f(int a = 1); }
@@ -448,6 +450,94 @@
 
 // dr34: na
 // dr35: dup 178
+
+namespace dr36 { // dr36: yes
+namespace example1 {
+  namespace A {
+int i;
+  }
+  
+  namespace A1 {
+using A::i;
+using A::i;
+  }
+  
+  void f()
+  {
+using A::i;
+using A::i;
+  }
+}
+
+namespace example2 {
+  struct A
+  {
+int i;
+static int j;
+  };
+
+  struct B : A { };
+  struct C : A { };
+
+  struct D : virtual B, virtual C
+  {
+using B::i; // expected-note {{previous using declaration}}
+using B::i; // expected-error {{redeclaration of using declaration}}
+
+using C::i; // expected-note {{previous using declaration}}
+using C::i; // expected-error {{redeclaration of using declaration}}
+
+using B::j; // expected-note {{previous using declaration}}
+using B::j; // expected-error {{redeclaration of using declaration}}
+
+using C::j; // expected-note {{previous using declaration}}
+using C::j; // expected-error {{redeclaration of using declaration}}
+  };
+}
+
+namespace example3 {
+  template
+  struct A
+  {
+T i;
+static T j;
+  };
+
+  template
+  struct B : A { };
+  template
+  struct C : A { };
+
+  template
+  struct D : virtual B, virtual C
+  {
+using B::i; // expected-note {{previous using declaration}}
+using B::i; // expected-error {{redeclaration of using declaration}}
+
+using C::i; // expected-note {{previous using declaration}}
+using C::i; // expected-error {{redeclaration of using declaration}}
+
+using B::j; // expected-note {{previous using declaration}}
+using B::j; // expected-error {{redeclaration of using declaration}}
+
+using C::j; // expected-note {{previous using declaration}}
+using C::j; // expected-error {{redeclaration of using declaration}}
+  };
+}
+namespace example4 {
+  template
+  struct E {
+T k;
+  };
+
+  template
+  struct G : E {
+using E::k; // expected-note {{previous using declaration}}
+using E::k; // expected-error {{redeclaration of using declaration}}
+  };
+}
+}
+
 // dr37: sup 475
 
 namespace dr38 { // dr38: yes
@@ -699,6 +789,8 @@
 }
 
 namespace dr59 { // dr59: yes
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-volatile"
   template struct convert_to { operator T() const; };
   struct A {}; // expected-note 5+{{candidate}}
   struct B : A {}; // expected-note 0+{{candidate}}
@@ -732,6 +824,7 @@
   int n3 = convert_to();
   int n4 = convert_to();
   int n5 = convert_to();
+#pragma clang diagnostic pop
 }
 
 namespace dr60 { // dr60: yes
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f5993fc - [clang] Add test for CWG36

2022-12-01 Thread Vlad Serebrennikov via cfe-commits

Author: Vlad Serebrennikov
Date: 2022-12-01T21:10:28+03:00
New Revision: f5993fc7757e37a9076c5cd22de8f275e5c6097e

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

LOG: [clang] Add test for CWG36

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

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

Added: 


Modified: 
clang/test/CXX/drs/dr0xx.cpp
clang/www/cxx_dr_status.html

Removed: 




diff  --git a/clang/test/CXX/drs/dr0xx.cpp b/clang/test/CXX/drs/dr0xx.cpp
index 2959f4ebba91..e34dc75a1b6c 100644
--- a/clang/test/CXX/drs/dr0xx.cpp
+++ b/clang/test/CXX/drs/dr0xx.cpp
@@ -2,6 +2,8 @@
 // RUN: %clang_cc1 -std=c++11 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
 // RUN: %clang_cc1 -std=c++14 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
 // RUN: %clang_cc1 -std=c++17 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
+// RUN: %clang_cc1 -std=c++20 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
+// RUN: %clang_cc1 -std=c++2b %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
 
 namespace dr1 { // dr1: no
   namespace X { extern "C" void dr1_f(int a = 1); }
@@ -448,6 +450,94 @@ namespace dr33 { // dr33: yes
 
 // dr34: na
 // dr35: dup 178
+
+namespace dr36 { // dr36: yes
+namespace example1 {
+  namespace A {
+int i;
+  }
+  
+  namespace A1 {
+using A::i;
+using A::i;
+  }
+  
+  void f()
+  {
+using A::i;
+using A::i;
+  }
+}
+
+namespace example2 {
+  struct A
+  {
+int i;
+static int j;
+  };
+
+  struct B : A { };
+  struct C : A { };
+
+  struct D : virtual B, virtual C
+  {
+using B::i; // expected-note {{previous using declaration}}
+using B::i; // expected-error {{redeclaration of using declaration}}
+
+using C::i; // expected-note {{previous using declaration}}
+using C::i; // expected-error {{redeclaration of using declaration}}
+
+using B::j; // expected-note {{previous using declaration}}
+using B::j; // expected-error {{redeclaration of using declaration}}
+
+using C::j; // expected-note {{previous using declaration}}
+using C::j; // expected-error {{redeclaration of using declaration}}
+  };
+}
+
+namespace example3 {
+  template
+  struct A
+  {
+T i;
+static T j;
+  };
+
+  template
+  struct B : A { };
+  template
+  struct C : A { };
+
+  template
+  struct D : virtual B, virtual C
+  {
+using B::i; // expected-note {{previous using declaration}}
+using B::i; // expected-error {{redeclaration of using declaration}}
+
+using C::i; // expected-note {{previous using declaration}}
+using C::i; // expected-error {{redeclaration of using declaration}}
+
+using B::j; // expected-note {{previous using declaration}}
+using B::j; // expected-error {{redeclaration of using declaration}}
+
+using C::j; // expected-note {{previous using declaration}}
+using C::j; // expected-error {{redeclaration of using declaration}}
+  };
+}
+namespace example4 {
+  template
+  struct E {
+T k;
+  };
+
+  template
+  struct G : E {
+using E::k; // expected-note {{previous using declaration}}
+using E::k; // expected-error {{redeclaration of using declaration}}
+  };
+}
+}
+
 // dr37: sup 475
 
 namespace dr38 { // dr38: yes
@@ -699,6 +789,8 @@ namespace dr58 { // dr58: yes
 }
 
 namespace dr59 { // dr59: yes
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-volatile"
   template struct convert_to { operator T() const; };
   struct A {}; // expected-note 5+{{candidate}}
   struct B : A {}; // expected-note 0+{{candidate}}
@@ -732,6 +824,7 @@ namespace dr59 { // dr59: yes
   int n3 = convert_to();
   int n4 = convert_to();
   int n5 = convert_to();
+#pragma clang diagnostic pop
 }
 
 namespace dr60 { // dr60: yes

diff  --git a/clang/www/cxx_dr_status.html b/clang/www/cxx_dr_status.html
index e4d0a24e08c9..6fa7ead4138d 100755
--- a/clang/www/cxx_dr_status.html
+++ b/clang/www/cxx_dr_status.html
@@ -254,7 +254,7 @@ C++ defect report implementation status
 https://wg21.link/cwg36;>36
 CD6
 using-declarations in multiple-declaration contexts
-Unknown
+Yes
   
   
 https://wg21.link/cwg37;>37



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


[PATCH] D128677: [clangd] Support #import insertions

2022-12-01 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 479343.
dgoldman added a comment.

Run clang-format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128677

Files:
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/Headers.h
  clang-tools-extra/clangd/IncludeFixer.cpp
  clang-tools-extra/clangd/IncludeFixer.h
  clang-tools-extra/clangd/unittests/HeadersTests.cpp
  clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
  clang/lib/Tooling/Inclusions/HeaderIncludes.cpp

Index: clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
===
--- clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
+++ clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
@@ -342,7 +342,8 @@
 }
 
 llvm::Optional
-HeaderIncludes::insert(llvm::StringRef IncludeName, bool IsAngled) const {
+HeaderIncludes::insert(llvm::StringRef IncludeName, bool IsAngled,
+   bool IsImport) const {
   assert(IncludeName == trimInclude(IncludeName));
   // If a  ("header") already exists in code, "header" () with
   // different quotation will still be inserted.
@@ -372,7 +373,8 @@
   }
   assert(InsertOffset <= Code.size());
   std::string NewInclude =
-  std::string(llvm::formatv("#include {0}\n", QuotedName));
+  IsImport ? std::string(llvm::formatv("#import {0}\n", QuotedName))
+   : std::string(llvm::formatv("#include {0}\n", QuotedName));
   // When inserting headers at end of the code, also append '\n' to the code
   // if it does not end with '\n'.
   // FIXME: when inserting multiple #includes at the end of code, only one
Index: clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
===
--- clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
+++ clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
@@ -51,9 +51,9 @@
   HeaderIncludes(llvm::StringRef FileName, llvm::StringRef Code,
  const IncludeStyle );
 
-  /// Inserts an #include directive of \p Header into the code. If \p IsAngled
-  /// is true, \p Header will be quoted with <> in the directive; otherwise, it
-  /// will be quoted with "".
+  /// Inserts an #include or #import directive of \p Header into the code.
+  /// If \p IsAngled is true, \p Header will be quoted with <> in the directive;
+  /// otherwise, it will be quoted with "".
   ///
   /// When searching for points to insert new header, this ignores #include's
   /// after the #include block(s) in the beginning of a file to avoid inserting
@@ -70,13 +70,13 @@
   /// same category in the code that should be sorted after \p IncludeName. If
   /// \p IncludeName already exists (with exactly the same spelling), this
   /// returns None.
-  llvm::Optional insert(llvm::StringRef Header,
-  bool IsAngled) const;
+  llvm::Optional
+  insert(llvm::StringRef Header, bool IsAngled, bool IsImport = false) const;
 
   /// Removes all existing #includes of \p Header quoted with <> if \p IsAngled
   /// is true or "" if \p IsAngled is false.
-  /// This doesn't resolve the header file path; it only deletes #includes with
-  /// exactly the same spelling.
+  /// This doesn't resolve the header file path; it only deletes #includes and
+  /// #imports with exactly the same spelling.
   tooling::Replacements remove(llvm::StringRef Header, bool IsAngled) const;
 
   // Matches a whole #include directive.
Index: clang-tools-extra/clangd/unittests/HeadersTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeadersTests.cpp
+++ clang-tools-extra/clangd/unittests/HeadersTests.cpp
@@ -117,7 +117,8 @@
 return Path.value_or("");
   }
 
-  llvm::Optional insert(llvm::StringRef VerbatimHeader) {
+  llvm::Optional insert(llvm::StringRef VerbatimHeader,
+  bool ViaImport) {
 Clang = setupClang();
 PreprocessOnlyAction Action;
 EXPECT_TRUE(
@@ -126,7 +127,7 @@
 IncludeInserter Inserter(MainFile, /*Code=*/"", format::getLLVMStyle(),
  CDB.getCompileCommand(MainFile)->Directory,
  >getPreprocessor().getHeaderSearchInfo());
-auto Edit = Inserter.insert(VerbatimHeader);
+auto Edit = Inserter.insert(VerbatimHeader, ViaImport);
 Action.EndSourceFile();
 return Edit;
   }
@@ -330,9 +331,13 @@
 }
 
 TEST_F(HeadersTest, PreferInserted) {
-  auto Edit = insert("");
+  auto Edit = insert("", /*ViaImport=*/false);
   EXPECT_TRUE(Edit);
-  EXPECT_TRUE(StringRef(Edit->newText).contains(""));
+  EXPECT_EQ(Edit->newText, "#include \n");
+
+  Edit = insert("\"header.h\"", /*ViaImport=*/true);
+  EXPECT_TRUE(Edit);
+  EXPECT_EQ(Edit->newText, "#import \"header.h\"\n");
 }
 
 TEST(Headers, NoHeaderSearchInfo) {
Index: 

  1   2   3   >