[PATCH] D143148: [clang-repl] Add basic multiline input support

2023-02-15 Thread Vassil Vassilev via Phabricator via cfe-commits
v.g.vassilev added inline comments.



Comment at: clang/lib/Interpreter/IncrementalParser.cpp:260
+ std::error_code());
+Token Tok;
+do {

I think we can simplify the heuristics here by asking if the end source 
location of the last created declaration is the same as the parser/lexer 
current token that is observed before EOF. If that's the case, then we are 
done. If not we can request more input.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143148

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


[clang] ddc5d40 - [clang][analyzer] Make messages of StdCLibraryFunctionsChecker user-friendly

2023-02-15 Thread Balázs Kéri via cfe-commits

Author: Balázs Kéri
Date: 2023-02-15T09:22:48+01:00
New Revision: ddc5d40dd285d6422dc66b9aa25064502af3218b

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

LOG: [clang][analyzer] Make messages of StdCLibraryFunctionsChecker 
user-friendly

Warnings and notes of checker alpha.unix.StdLibraryFunctionArgs are
improved. Previously one warning and one note was emitted for every
finding, now one warning is emitted only that contains a detailed
description of the found issue.

Reviewed By: Szelethus

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
clang/test/Analysis/std-c-library-functions-arg-constraints-note-tags.cpp
clang/test/Analysis/std-c-library-functions-arg-constraints-notes.cpp
clang/test/Analysis/std-c-library-functions-arg-constraints-tracking-notes.c
clang/test/Analysis/std-c-library-functions-arg-constraints.c
clang/test/Analysis/std-c-library-functions-arg-constraints.cpp
clang/test/Analysis/stream-note.c
clang/test/Analysis/stream-stdlibraryfunctionargs.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index 49b3db560843d..b36f72f2653c7 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -84,9 +84,20 @@ class StdLibraryFunctionsChecker
   typedef uint32_t ArgNo;
   static const ArgNo Ret;
 
+  using DescString = SmallString<96>;
   /// Returns the string representation of an argument index.
   /// E.g.: (1) -> '1st arg', (2) - > '2nd arg'
   static SmallString<8> getArgDesc(ArgNo);
+  /// Append textual description of a numeric range [RMin,RMax] to the string
+  /// 'Out'.
+  static void appendInsideRangeDesc(llvm::APSInt RMin, llvm::APSInt RMax,
+QualType ArgT, BasicValueFactory &BVF,
+DescString &Out);
+  /// Append textual description of a numeric range out of [RMin,RMax] to the
+  /// string 'Out'.
+  static void appendOutOfRangeDesc(llvm::APSInt RMin, llvm::APSInt RMax,
+   QualType ArgT, BasicValueFactory &BVF,
+   DescString &Out);
 
   class ValueConstraint;
 
@@ -101,6 +112,12 @@ class StdLibraryFunctionsChecker
   /// (or return value) of a function. Derived classes implement 
diff erent kind
   /// of constraints, e.g range constraints or correlation between two
   /// arguments.
+  /// These are used as argument constraints (preconditions) of functions, in
+  /// which case a bug report may be emitted if the constraint is not 
satisfied.
+  /// Another use is as conditions for summary cases, to create 
diff erent
+  /// classes of behavior for a function. In this case no description of the
+  /// constraint is needed because the summary cases have an own (not 
generated)
+  /// description string.
   class ValueConstraint {
   public:
 ValueConstraint(ArgNo ArgN) : ArgN(ArgN) {}
@@ -114,9 +131,9 @@ class StdLibraryFunctionsChecker
   llvm_unreachable("Not implemented");
 };
 
-// Check whether the constraint is malformed or not. It is malformed if the
-// specified argument has a mismatch with the given FunctionDecl (e.g. the
-// arg number is out-of-range of the function's argument list).
+/// Check whether the constraint is malformed or not. It is malformed if 
the
+/// specified argument has a mismatch with the given FunctionDecl (e.g. the
+/// arg number is out-of-range of the function's argument list).
 bool checkValidity(const FunctionDecl *FD) const {
   const bool ValidArg = ArgN == Ret || ArgN < FD->getNumParams();
   assert(ValidArg && "Arg out of range!");
@@ -127,31 +144,34 @@ class StdLibraryFunctionsChecker
 }
 ArgNo getArgNo() const { return ArgN; }
 
-// Return those arguments that should be tracked when we report a bug. By
-// default it is the argument that is constrained, however, in some special
-// cases we need to track other arguments as well. E.g. a buffer size might
-// be encoded in another argument.
+/// Return those arguments that should be tracked when we report a bug. By
+/// default it is the argument that is constrained, however, in some 
special
+/// cases we need to track other arguments as well. E.g. a buffer size 
might
+/// be encoded in another argument.
 virtual std::vector getArgsToTrack() const { return {ArgN}; }
 
 virtual StringRef getName() const = 0;
 
-// Represents that in which context do we require a description of the
-// constraint.
+/

[PATCH] D143194: [clang][analyzer] Make messages of StdCLibraryFunctionsChecker user-friendly

2023-02-15 Thread Balázs Kéri 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 rGddc5d40dd285: [clang][analyzer] Make messages of 
StdCLibraryFunctionsChecker user-friendly (authored by balazske).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143194

Files:
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/test/Analysis/std-c-library-functions-arg-constraints-note-tags.cpp
  clang/test/Analysis/std-c-library-functions-arg-constraints-notes.cpp
  clang/test/Analysis/std-c-library-functions-arg-constraints-tracking-notes.c
  clang/test/Analysis/std-c-library-functions-arg-constraints.c
  clang/test/Analysis/std-c-library-functions-arg-constraints.cpp
  clang/test/Analysis/stream-note.c
  clang/test/Analysis/stream-stdlibraryfunctionargs.c

Index: clang/test/Analysis/stream-stdlibraryfunctionargs.c
===
--- clang/test/Analysis/stream-stdlibraryfunctionargs.c
+++ clang/test/Analysis/stream-stdlibraryfunctionargs.c
@@ -18,37 +18,31 @@
 void test_fopen(void) {
   FILE *fp = fopen("path", "r");
   clang_analyzer_eval(fp != NULL); // any-warning{{TRUE}} any-warning{{FALSE}}
-  fclose(fp); // stdargs-warning{{Function argument constraint is not satisfied}} \
-  // stdargs-note{{The 1st argument should not be NULL}}
+  fclose(fp); // stdargs-warning{{should not be NULL}}
 }
 
 void test_tmpfile(void) {
   FILE *fp = tmpfile();
   clang_analyzer_eval(fp != NULL); // any-warning{{TRUE}} any-warning{{FALSE}}
-  fclose(fp); // stdargs-warning{{Function argument constraint is not satisfied}} \
-  // stdargs-note{{The 1st argument should not be NULL}}
+  fclose(fp); // stdargs-warning{{should not be NULL}}
 }
 
 void test_fclose(void) {
   FILE *fp = tmpfile();
-  fclose(fp); // stdargs-warning{{Function argument constraint is not satisfied}} \
-  // stdargs-note{{The 1st argument should not be NULL}}
+  fclose(fp); // stdargs-warning{{should not be NULL}}
   clang_analyzer_eval(fp != NULL); // any-warning{{TRUE}}
 }
 
 void test_freopen(void) {
   FILE *fp = tmpfile();
-  fp = freopen("file", "w", fp); // stdargs-warning{{Function argument constraint is not satisfied}} \
- // stdargs-note{{The 3rd argument should not be NULL}}
-  fclose(fp); // stdargs-warning{{Function argument constraint is not satisfied}} \
-  // stdargs-note{{The 1st argument should not be NULL}}
+  fp = freopen("file", "w", fp); // stdargs-warning{{should not be NULL}}
+  fclose(fp); // stdargs-warning{{should not be NULL}}
   clang_analyzer_eval(fp != NULL); // any-warning{{TRUE}}
 }
 
 void test_fread(void) {
   FILE *fp = tmpfile();
-  size_t ret = fread(buf, size, n, fp); // stdargs-warning{{Function argument constraint is not satisfied}} \
-// stdargs-note{{The 4th argument should not be NULL}}
+  size_t ret = fread(buf, size, n, fp); // stdargs-warning{{The 4th argument to 'fread' should not be NULL}}
   clang_analyzer_eval(fp != NULL); // any-warning{{TRUE}}
   clang_analyzer_eval(ret <= n); // any-warning{{TRUE}}
   clang_analyzer_eval(ret == n); // any-warning{{TRUE}} any-warning{{FALSE}}
@@ -58,8 +52,7 @@
 
 void test_fwrite(void) {
   FILE *fp = tmpfile();
-  size_t ret = fwrite(buf, size, n, fp); // stdargs-warning{{Function argument constraint is not satisfied}} \
-// stdargs-note{{The 4th argument should not be NULL}}
+  size_t ret = fwrite(buf, size, n, fp); // stdargs-warning{{The 4th argument to 'fwrite' should not be NULL}}
   clang_analyzer_eval(fp != NULL); // any-warning{{TRUE}}
   clang_analyzer_eval(ret <= n); // any-warning{{TRUE}}
   clang_analyzer_eval(ret == n); // any-warning{{TRUE}} any-warning{{FALSE}}
@@ -69,24 +62,21 @@
 
 void test_fseek(void) {
   FILE *fp = tmpfile();
-  fseek(fp, 0, 0); // stdargs-warning{{Function argument constraint is not satisfied}} \
-   // stdargs-note{{The 1st argument should not be NULL}}
+  fseek(fp, 0, 0); // stdargs-warning{{should not be NULL}}
   clang_analyzer_eval(fp != NULL); // any-warning{{TRUE}}
   fclose(fp);
 }
 
 void test_ftell(void) {
   FILE *fp = tmpfile();
-  ftell(fp); // stdargs-warning{{Function argument constraint is not satisfied}} \
- // stdargs-note{{The 1st argument should not be NULL}}
+  ftell(fp); // stdargs-warning{{should not be NULL}}
   clang_analyzer_eval(fp != NULL); // any-warning{{TRUE}}
   fclose(fp);
 }
 
 void test_rewind(void) {
   FILE *fp = tmpfile();
-  rewind(fp); // stdargs-warning{{Function argument constraint is not satisfied}} \
-  // stdargs-note{{The 1st argument should not be NULL}}
+  rewind(fp); // stdargs-warning{{should not be NULL}}
   clang_analyzer_eval(fp != NULL); // any-warning{{TRUE}}
   fclo

[PATCH] D144054: [Lex] Fix a crash in updateConsecutiveMacroArgTokens.

2023-02-15 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang/lib/Lex/TokenLexer.cpp:1023
 Partition = All.take_while([&](const Token &T) {
-  return T.getLocation() >= BeginLoc && T.getLocation() < Limit &&
- NearLast(T.getLocation());
+  // NOTE: the Limit is included! In general, all token locations
+  // should be within [BeginLoc, Limit) range. However, the clang

shafik wrote:
> You had refactored the previous version, was this the way it was handled 
> before? Do we need to add more test to ensure that we don't have any other 
> unintended issues?
>  was this the way it was handled before?
Yeah, the previous implementation literally checked whether every token is from 
the same file id by calling `getFileID`.

> Do we need to add more test to ensure that we don't have any other unintended 
> issues?

I'd like to add more, but it is hard to foresee all invalid cases (clang has 
different error-recovery strategies that might have different side effects). 



Comment at: clang/lib/Lex/TokenLexer.cpp:1031
+  //
+  // See https://github.com/llvm/llvm-project/issues/60722.
+  return T.getLocation() >= BeginLoc && T.getLocation() <= Limit

shafik wrote:
> I don't believe we include links to issues in comments but you should 
> definitely add the information to the commit message and when folks look at 
> the commit they can get the that context there.
I'm happy to remove it. But is there any guideline discouraging this practise? 
I have already seen this pattern in LLVM project. I think this is based on the 
author's judgement (IMO, it seems better to keep it for this case).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144054

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


[PATCH] D140795: [Flang] Add user option -funderscoring/-fnounderscoring to control trailing underscore added to external names

2023-02-15 Thread Valentin Clement via Phabricator via cfe-commits
clementval added a comment.

The pre-commit check is still failing with these tests:

Flang :: Fir/alloc.fir

  Flang :: Fir/embox.fir
  Flang :: Fir/optional.fir
  Flang :: Fir/rebox.fir
  Flang :: Lower/common-block.f90
  Flang :: Lower/forall/character-1.f90


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

https://reviews.llvm.org/D140795

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


[PATCH] D143851: [clang-tidy] Tweak 'rule of 3/5' checks to allow defaulting a destructor outside the class.

2023-02-15 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added a comment.

> That's not so simple. At work we use clang-tidy for few big projects. I had 
> to explicitly add to some checks `unless(isExpansionInSystemHeader())` to 
> gain some performance improvement of clang-tidy. This check is one of them.
> Problem is that some matchers or `check` methods in checks are heavy, and 
> when you got lot of system headers (boost, STL, generated interfaces, message 
> structs, ...) you may end up easily with hundreds of hidden issues from 
> single translation unit.
> For some checks explicit exclude of system headers gives ~50% performance 
> improvement, that result in faster CI feedback.
>
> Best would be to have something more generic like: if --system-headers is not 
> used, then exclude code as early as possible, before even constructing 
> diagnostic information.

Yes, I meant from a "diagnostic" point of view. I agree that performance-wise 
it's a lot of work that is discarded at the end and would be good to avoid as 
early as possible. This sounds like something all checks would benefit from, so 
finding a general solution to that problem would be good. I believe the best 
forum to discuss this would be an RFC in Discourse, make sure to tag @njames93 
as Code Owner.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143851

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


[PATCH] D141785: [Clang][LoongArch] Implement patchable function entry

2023-02-15 Thread WÁNG Xuěruì via Phabricator via cfe-commits
xen0n updated this revision to Diff 497596.
xen0n added a comment.

Rebase and change to lower the op in LoongArchAsmPrinter so as to make people's 
lives easier when they come to rebase D141785 
 on top of this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141785

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/fpatchable-function-entry.c
  clang/test/Sema/patchable-function-entry-attr.cpp
  llvm/lib/Target/LoongArch/LoongArchAsmPrinter.cpp
  llvm/lib/Target/LoongArch/LoongArchAsmPrinter.h
  llvm/lib/Target/LoongArch/LoongArchInstrInfo.cpp
  llvm/lib/Target/LoongArch/LoongArchInstrInfo.h
  llvm/test/CodeGen/LoongArch/patchable-function-entry.ll

Index: llvm/test/CodeGen/LoongArch/patchable-function-entry.ll
===
--- /dev/null
+++ llvm/test/CodeGen/LoongArch/patchable-function-entry.ll
@@ -0,0 +1,63 @@
+;; Test the function attribute "patchable-function-entry".
+;; Adapted from the RISCV test case.
+; RUN: llc --mtriple=loongarch32 < %s | FileCheck %s --check-prefixes=CHECK,LA32
+; RUN: llc --mtriple=loongarch64 < %s | FileCheck %s --check-prefixes=CHECK,LA64
+
+define void @f0() "patchable-function-entry"="0" {
+; CHECK-LABEL: f0:
+; CHECK-NEXT:  .Lfunc_begin0:
+; CHECK-NOT: nop
+; CHECK: ret
+; CHECK-NOT:   .section __patchable_function_entries
+  ret void
+}
+
+define void @f1() "patchable-function-entry"="1" {
+; CHECK-LABEL: f1:
+; CHECK-NEXT: .Lfunc_begin1:
+; CHECK: nop
+; CHECK-NEXT:ret
+; CHECK:   .section __patchable_function_entries,"awo",@progbits,f1{{$}}
+; LA32:.p2align 2
+; LA32-NEXT:   .word .Lfunc_begin1
+; LA64:.p2align 3
+; LA64-NEXT:   .dword .Lfunc_begin1
+  ret void
+}
+
+$f5 = comdat any
+define void @f5() "patchable-function-entry"="5" comdat {
+; CHECK-LABEL:   f5:
+; CHECK-NEXT:.Lfunc_begin2:
+; CHECK-COUNT-5:   nop
+; CHECK-NEXT:  ret
+; CHECK: .section __patchable_function_entries,"aGwo",@progbits,f5,comdat,f5{{$}}
+; LA32:  .p2align 2
+; LA32-NEXT: .word .Lfunc_begin2
+; LA64:  .p2align 3
+; LA64-NEXT: .dword .Lfunc_begin2
+  ret void
+}
+
+;; -fpatchable-function-entry=3,2
+;; "patchable-function-prefix" emits data before the function entry label.
+define void @f3_2() "patchable-function-entry"="1" "patchable-function-prefix"="2" {
+; CHECK-LABEL:   .type f3_2,@function
+; CHECK-NEXT:.Ltmp0: # @f3_2
+; CHECK-COUNT-2:   nop
+; CHECK-NEXT:f3_2:
+; CHECK: # %bb.0:
+; CHECK-NEXT:  nop
+; LA32-NEXT:   addi.w $sp, $sp, -16
+; LA64-NEXT:   addi.d $sp, $sp, -16
+;; .size does not include the prefix.
+; CHECK:  .Lfunc_end3:
+; CHECK-NEXT: .size f3_2, .Lfunc_end3-f3_2
+; CHECK:  .section __patchable_function_entries,"awo",@progbits,f3_2{{$}}
+; LA32:   .p2align 2
+; LA32-NEXT:  .word .Ltmp0
+; LA64:   .p2align 3
+; LA64-NEXT:  .dword .Ltmp0
+  %frame = alloca i8, i32 16
+  ret void
+}
Index: llvm/lib/Target/LoongArch/LoongArchInstrInfo.h
===
--- llvm/lib/Target/LoongArch/LoongArchInstrInfo.h
+++ llvm/lib/Target/LoongArch/LoongArchInstrInfo.h
@@ -27,6 +27,8 @@
 public:
   explicit LoongArchInstrInfo(LoongArchSubtarget &STI);
 
+  MCInst getNop() const override;
+
   void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
const DebugLoc &DL, MCRegister DstReg, MCRegister SrcReg,
bool KillSrc) const override;
Index: llvm/lib/Target/LoongArch/LoongArchInstrInfo.cpp
===
--- llvm/lib/Target/LoongArch/LoongArchInstrInfo.cpp
+++ llvm/lib/Target/LoongArch/LoongArchInstrInfo.cpp
@@ -17,6 +17,7 @@
 #include "MCTargetDesc/LoongArchMCTargetDesc.h"
 #include "MCTargetDesc/LoongArchMatInt.h"
 #include "llvm/CodeGen/RegisterScavenging.h"
+#include "llvm/MC/MCInstBuilder.h"
 
 using namespace llvm;
 
@@ -28,6 +29,13 @@
 LoongArch::ADJCALLSTACKUP),
   STI(STI) {}
 
+MCInst LoongArchInstrInfo::getNop() const {
+  return MCInstBuilder(LoongArch::ANDI)
+  .addReg(LoongArch::R0)
+  .addReg(LoongArch::R0)
+  .addImm(0);
+}
+
 void LoongArchInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
  MachineBasicBlock::iterator MBBI,
  const DebugLoc &DL, MCRegister DstReg,
Index: llvm/lib/Target/LoongArch/LoongArchAsmPrinter.h
===
--- llvm/lib/Target/LoongArch/LoongArchAsmPrinter.h
+++ llvm/lib/Target/LoongArch/LoongArchAsmPrinter.h
@@ -41,6 +41,8 @@
   bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
  const char *

[PATCH] D141785: [Clang][LoongArch] Implement patchable function entry

2023-02-15 Thread WÁNG Xuěruì via Phabricator via cfe-commits
xen0n updated this revision to Diff 497598.
xen0n added a comment.

Document the change in Clang release note.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141785

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/fpatchable-function-entry.c
  clang/test/Sema/patchable-function-entry-attr.cpp
  llvm/lib/Target/LoongArch/LoongArchAsmPrinter.cpp
  llvm/lib/Target/LoongArch/LoongArchAsmPrinter.h
  llvm/lib/Target/LoongArch/LoongArchInstrInfo.cpp
  llvm/lib/Target/LoongArch/LoongArchInstrInfo.h
  llvm/test/CodeGen/LoongArch/patchable-function-entry.ll

Index: llvm/test/CodeGen/LoongArch/patchable-function-entry.ll
===
--- /dev/null
+++ llvm/test/CodeGen/LoongArch/patchable-function-entry.ll
@@ -0,0 +1,63 @@
+;; Test the function attribute "patchable-function-entry".
+;; Adapted from the RISCV test case.
+; RUN: llc --mtriple=loongarch32 < %s | FileCheck %s --check-prefixes=CHECK,LA32
+; RUN: llc --mtriple=loongarch64 < %s | FileCheck %s --check-prefixes=CHECK,LA64
+
+define void @f0() "patchable-function-entry"="0" {
+; CHECK-LABEL: f0:
+; CHECK-NEXT:  .Lfunc_begin0:
+; CHECK-NOT: nop
+; CHECK: ret
+; CHECK-NOT:   .section __patchable_function_entries
+  ret void
+}
+
+define void @f1() "patchable-function-entry"="1" {
+; CHECK-LABEL: f1:
+; CHECK-NEXT: .Lfunc_begin1:
+; CHECK: nop
+; CHECK-NEXT:ret
+; CHECK:   .section __patchable_function_entries,"awo",@progbits,f1{{$}}
+; LA32:.p2align 2
+; LA32-NEXT:   .word .Lfunc_begin1
+; LA64:.p2align 3
+; LA64-NEXT:   .dword .Lfunc_begin1
+  ret void
+}
+
+$f5 = comdat any
+define void @f5() "patchable-function-entry"="5" comdat {
+; CHECK-LABEL:   f5:
+; CHECK-NEXT:.Lfunc_begin2:
+; CHECK-COUNT-5:   nop
+; CHECK-NEXT:  ret
+; CHECK: .section __patchable_function_entries,"aGwo",@progbits,f5,comdat,f5{{$}}
+; LA32:  .p2align 2
+; LA32-NEXT: .word .Lfunc_begin2
+; LA64:  .p2align 3
+; LA64-NEXT: .dword .Lfunc_begin2
+  ret void
+}
+
+;; -fpatchable-function-entry=3,2
+;; "patchable-function-prefix" emits data before the function entry label.
+define void @f3_2() "patchable-function-entry"="1" "patchable-function-prefix"="2" {
+; CHECK-LABEL:   .type f3_2,@function
+; CHECK-NEXT:.Ltmp0: # @f3_2
+; CHECK-COUNT-2:   nop
+; CHECK-NEXT:f3_2:
+; CHECK: # %bb.0:
+; CHECK-NEXT:  nop
+; LA32-NEXT:   addi.w $sp, $sp, -16
+; LA64-NEXT:   addi.d $sp, $sp, -16
+;; .size does not include the prefix.
+; CHECK:  .Lfunc_end3:
+; CHECK-NEXT: .size f3_2, .Lfunc_end3-f3_2
+; CHECK:  .section __patchable_function_entries,"awo",@progbits,f3_2{{$}}
+; LA32:   .p2align 2
+; LA32-NEXT:  .word .Ltmp0
+; LA64:   .p2align 3
+; LA64-NEXT:  .dword .Ltmp0
+  %frame = alloca i8, i32 16
+  ret void
+}
Index: llvm/lib/Target/LoongArch/LoongArchInstrInfo.h
===
--- llvm/lib/Target/LoongArch/LoongArchInstrInfo.h
+++ llvm/lib/Target/LoongArch/LoongArchInstrInfo.h
@@ -27,6 +27,8 @@
 public:
   explicit LoongArchInstrInfo(LoongArchSubtarget &STI);
 
+  MCInst getNop() const override;
+
   void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
const DebugLoc &DL, MCRegister DstReg, MCRegister SrcReg,
bool KillSrc) const override;
Index: llvm/lib/Target/LoongArch/LoongArchInstrInfo.cpp
===
--- llvm/lib/Target/LoongArch/LoongArchInstrInfo.cpp
+++ llvm/lib/Target/LoongArch/LoongArchInstrInfo.cpp
@@ -17,6 +17,7 @@
 #include "MCTargetDesc/LoongArchMCTargetDesc.h"
 #include "MCTargetDesc/LoongArchMatInt.h"
 #include "llvm/CodeGen/RegisterScavenging.h"
+#include "llvm/MC/MCInstBuilder.h"
 
 using namespace llvm;
 
@@ -28,6 +29,13 @@
 LoongArch::ADJCALLSTACKUP),
   STI(STI) {}
 
+MCInst LoongArchInstrInfo::getNop() const {
+  return MCInstBuilder(LoongArch::ANDI)
+  .addReg(LoongArch::R0)
+  .addReg(LoongArch::R0)
+  .addImm(0);
+}
+
 void LoongArchInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
  MachineBasicBlock::iterator MBBI,
  const DebugLoc &DL, MCRegister DstReg,
Index: llvm/lib/Target/LoongArch/LoongArchAsmPrinter.h
===
--- llvm/lib/Target/LoongArch/LoongArchAsmPrinter.h
+++ llvm/lib/Target/LoongArch/LoongArchAsmPrinter.h
@@ -41,6 +41,8 @@
   bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
  const char *ExtraCode, raw_ostream &OS) override;
 
+  void LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI);
+
 

[PATCH] D143509: Move the BySpelling map to IncludeStructure.

2023-02-15 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 497602.
VitaNuo marked an inline comment as done.
VitaNuo added a comment.

Address review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143509

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/Headers.h
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/HeadersTests.cpp

Index: clang-tools-extra/clangd/unittests/HeadersTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeadersTests.cpp
+++ clang-tools-extra/clangd/unittests/HeadersTests.cpp
@@ -197,6 +197,39 @@
Distance(getID(BazHeader, Includes), 1u)));
 }
 
+TEST_F(HeadersTest, CacheBySpellingIsBuiltForMainInclusions) {
+  std::string FooHeader = testPath("foo.h");
+  FS.Files[FooHeader] = R"cpp(
+  void foo();
+)cpp";
+  std::string BarHeader = testPath("bar.h");
+  FS.Files[BarHeader] = R"cpp(
+  void bar();
+)cpp";
+  std::string BazHeader = testPath("baz.h");
+  FS.Files[BazHeader] = R"cpp(
+  void baz();
+)cpp";
+  FS.Files[MainFile] = R"cpp(
+#include "foo.h"
+#include "bar.h"
+#include "baz.h"
+)cpp";
+  auto Includes = collectIncludes();
+  EXPECT_THAT(Includes.MainFileIncludes,
+  UnorderedElementsAre(written("\"foo.h\""), written("\"bar.h\""),
+   written("\"baz.h\"")));
+  EXPECT_THAT(Includes.mainFileIncludesWithSpelling("\"foo.h\""),
+  UnorderedElementsAre(static_cast(
+  *(Includes.MainFileIncludes[0]).HeaderID)));
+  EXPECT_THAT(Includes.mainFileIncludesWithSpelling("\"bar.h\""),
+  UnorderedElementsAre(static_cast(
+  *(Includes.MainFileIncludes[1]).HeaderID)));
+  EXPECT_THAT(Includes.mainFileIncludesWithSpelling("\"baz.h\""),
+  UnorderedElementsAre(static_cast(
+  *(Includes.MainFileIncludes[2]).HeaderID)));
+}
+
 TEST_F(HeadersTest, PreambleIncludesPresentOnce) {
   // We use TestTU here, to ensure we use the preamble replay logic.
   // We're testing that the logic doesn't crash, and doesn't result in duplicate
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -85,7 +85,7 @@
 // Using templateName case is handled by the override TraverseTemplateName.
 if (TST->getTemplateName().getKind() == TemplateName::UsingTemplate)
   return true;
-add(TST->getAsCXXRecordDecl());  // Specialization
+add(TST->getAsCXXRecordDecl()); // Specialization
 return true;
   }
 
@@ -474,22 +474,16 @@
   translateToHeaderIDs(ReferencedFiles, AST.getIncludeStructure(), SM);
   return getUnused(AST, ReferencedHeaders, ReferencedFiles.SpelledUmbrellas);
 }
-std::vector computeUnusedIncludesExperimental(ParsedAST &AST) {
-   const auto &SM = AST.getSourceManager();
-   const auto &Includes = AST.getIncludeStructure();
-   // FIXME: this map should probably be in IncludeStructure.
-   llvm::StringMap> BySpelling;
-   for (const auto &Inc : Includes.MainFileIncludes) {
-if (Inc.HeaderID)
-  BySpelling.try_emplace(Inc.Written)
-  .first->second.push_back(
-  static_cast(*Inc.HeaderID));
-   }
-   // FIXME: !!this is a hacky way to collect macro references.
-   std::vector Macros;
-auto& PP = AST.getPreprocessor();
-   for (const syntax::Token &Tok :
-AST.getTokens().spelledTokens(SM.getMainFileID())) {
+std::vector
+computeUnusedIncludesExperimental(ParsedAST &AST) {
+  const auto &SM = AST.getSourceManager();
+  const auto &Includes = AST.getIncludeStructure();
+
+  // FIXME: !!this is a hacky way to collect macro references.
+  std::vector Macros;
+  auto &PP = AST.getPreprocessor();
+  for (const syntax::Token &Tok :
+   AST.getTokens().spelledTokens(SM.getMainFileID())) {
 auto Macro = locateMacroAt(Tok, PP);
 if (!Macro)
   continue;
@@ -499,31 +493,32 @@
include_cleaner::Macro{/*Name=*/PP.getIdentifierInfo(Tok.text(SM)),
   DefLoc},
include_cleaner::RefType::Explicit});
-   }
-   llvm::DenseSet Used;
-   include_cleaner::walkUsed(
-   AST.getLocalTopLevelDecls(), /*MacroRefs=*/Macros,
-   AST.getPragmaIncludes(), SM,
-   [&](const include_cleaner::SymbolReference &Ref,
-   llvm::ArrayRef Providers) {
- for (const auto &H : Providers) {
-   switch (H.kind()) {
-   case include_cleaner::Header::Physical:
- if (auto HeaderID = Includes.getID(H.physical()))
-   Used.insert(*HeaderID);
- break;
-   case include_cleaner::Header::Standard:
- for (auto HeaderID : Includes.StdlibHeaders.lookup(H.standard()))
-   Used.insert

[PATCH] D143509: Move the BySpelling map to IncludeStructure.

2023-02-15 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo added a comment.

Thanks for the review!




Comment at: clang-tools-extra/clangd/Headers.cpp:76
+Out->MainFileIncludesBySpelling.try_emplace(Inc.Written)
+.first->second.push_back(static_cast(*Inc.HeaderID));
   }

kadircet wrote:
> right now we're only storing "resolved" includes from the main file and not 
> all, this is creating a discrepancy between the view one gets through 
> `MainFileIncludes` and through this map.
> in addition to that only storing `HeaderID` gets the job done for 
> IncludeCleaner, but won't really help anyone that wants to match main file 
> includes apart from that (there's no easy way to go from a `HeaderID` to an 
> `Inclusion`).
> 
> so instead of storing the `HeaderID` in the map values, we can actually store 
> indexes into `MainFileIncludes`. later on during the lookup, we can build a 
> `SmallVector` that contains pointers to the relevant includes. 
> WDYT?
Ok sure.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143509

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


[PATCH] D143070: [clang-format] Enable FormatTokenSource to insert tokens.

2023-02-15 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Format/FormatTokenSource.h:74
 public:
-  IndexedTokenSource(ArrayRef Tokens)
+  IndexedTokenSource(SmallVectorImpl &Tokens)
   : Tokens(Tokens), Position(-1) {}

klimek wrote:
> sammccall wrote:
> > As I understand it, this parameter is used:
> >  - to provide the initial set of input tokens the source will iterate over
> >  - as a common address space for input + synthesized tokens, to allow the 
> > jump mechanism to work
> >  - to make the caller responsible for ownership/lifetime of the synthesized 
> > tokens too
> > 
> > This simplifies the implementation, my only problem with this is it seems 
> > unusual and confusing.
> > A comment explaining the roles of this `Tokens` param would help a bit.
> > 
> > Alternatively you could consider slightly different data structures just 
> > for the purpose of making interfaces more obvious: e.g. pass in a 
> > `BumpPtrAllocator&`, allocate scratch tokens there, and use pointers 
> > instead of indices (jumps become a ptr->ptr map etc)
> Noticing none of this makes sense. We should really just copy the tokens, 
> given that we modify the vector.
Oops, somehow I missed that this was an array of *pointers* and assumed that 
copying it was no good. This is much better.



Comment at: clang/lib/Format/UnwrappedLineParser.h:287
   // owned outside of and handed into the UnwrappedLineParser.
+  // FIXME: The above fixme doesn't work if we need to create tokens while
+  // parsing.

I'm not really sure how to read the combination of these two FIXMEs... does it 
mean "we wanted to do this differently one day, but now we never can"?

Maybe either delete both, or if you think it's still potentially actionable, 
something like FIXME: it would be better to have tokens created and owned 
outside because XYZ, but it's hard because macro expansion mutates the stream

(I don't really understand what the prev comment is about: the tokens *are* 
handed into the UnwrappedLineParser constructor. So I may be off base here)



Comment at: clang/unittests/Format/FormatTokenSourceTest.cpp:36
+FormatToken *Tok = FormatTok;  
\
+EXPECT_EQ((Tok)->Tok.getKind(), tok::identifier) << *(Tok);
\
+EXPECT_EQ((Tok)->TokenText, Name) << *(Tok);   
\

nit: parens on (Tok) are redundant given Tok is a local rather than the macro 
arg


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143070

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


[clang-tools-extra] 45ddc15 - [clang-tidy][NFC] Remove ModernizeTidyModule::getModuleOptions

2023-02-15 Thread Carlos Galvez via cfe-commits

Author: Carlos Galvez
Date: 2023-02-15T10:38:36Z
New Revision: 45ddc157ca7c464ebbea627da0f682b1554e2390

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

LOG: [clang-tidy][NFC] Remove ModernizeTidyModule::getModuleOptions

Most of the options stated there are duplicated already in
the implementation of each check as a default value for
each option.

The only place where this is not the case is the nullptr
check. Move the default option there instead. Only the
HICPP guidelines alias this modernize check, and there is
nothing in the documentation that suggests it should have
a different default value than the main modernize check.

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp 
b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
index 97d24e52e57f6..9f116f92c1fb1 100644
--- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -100,23 +100,6 @@ class ModernizeModule : public ClangTidyModule {
 "modernize-use-uncaught-exceptions");
 CheckFactories.registerCheck("modernize-use-using");
   }
-
-  ClangTidyOptions getModuleOptions() override {
-ClangTidyOptions Options;
-auto &Opts = Options.CheckOptions;
-// For types whose size in bytes is above this threshold, we prefer taking 
a
-// const-reference than making a copy.
-Opts["modernize-loop-convert.MaxCopySize"] = "16";
-
-Opts["modernize-loop-convert.MinConfidence"] = "reasonable";
-Opts["modernize-loop-convert.NamingStyle"] = "CamelCase";
-Opts["modernize-pass-by-value.IncludeStyle"] = "llvm";// Also: 
"google".
-Opts["modernize-replace-auto-ptr.IncludeStyle"] = "llvm"; // Also: 
"google".
-
-// Comma-separated list of macros that behave like NULL.
-Opts["modernize-use-nullptr.NullMacros"] = "NULL";
-return Options;
-  }
 };
 
 // Register the ModernizeTidyModule using this statically initialized variable.

diff  --git a/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
index 927033449b331..47c647841d760 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
@@ -480,7 +480,7 @@ class CastSequenceVisitor : public 
RecursiveASTVisitor {
 
 UseNullptrCheck::UseNullptrCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
-  NullMacrosStr(Options.get("NullMacros", "")) {
+  NullMacrosStr(Options.get("NullMacros", "NULL")) {
   StringRef(NullMacrosStr).split(NullMacros, ",");
 }
 



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


[PATCH] D143843: [clang-tidy][NFC] Remove ModernizeTidyModule::getModuleOptions

2023-02-15 Thread Carlos Galvez via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG45ddc157ca7c: [clang-tidy][NFC] Remove 
ModernizeTidyModule::getModuleOptions (authored by carlosgalvezp).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143843

Files:
  clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
  clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp


Index: clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
@@ -480,7 +480,7 @@
 
 UseNullptrCheck::UseNullptrCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
-  NullMacrosStr(Options.get("NullMacros", "")) {
+  NullMacrosStr(Options.get("NullMacros", "NULL")) {
   StringRef(NullMacrosStr).split(NullMacros, ",");
 }
 
Index: clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -100,23 +100,6 @@
 "modernize-use-uncaught-exceptions");
 CheckFactories.registerCheck("modernize-use-using");
   }
-
-  ClangTidyOptions getModuleOptions() override {
-ClangTidyOptions Options;
-auto &Opts = Options.CheckOptions;
-// For types whose size in bytes is above this threshold, we prefer taking 
a
-// const-reference than making a copy.
-Opts["modernize-loop-convert.MaxCopySize"] = "16";
-
-Opts["modernize-loop-convert.MinConfidence"] = "reasonable";
-Opts["modernize-loop-convert.NamingStyle"] = "CamelCase";
-Opts["modernize-pass-by-value.IncludeStyle"] = "llvm";// Also: 
"google".
-Opts["modernize-replace-auto-ptr.IncludeStyle"] = "llvm"; // Also: 
"google".
-
-// Comma-separated list of macros that behave like NULL.
-Opts["modernize-use-nullptr.NullMacros"] = "NULL";
-return Options;
-  }
 };
 
 // Register the ModernizeTidyModule using this statically initialized variable.


Index: clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
@@ -480,7 +480,7 @@
 
 UseNullptrCheck::UseNullptrCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
-  NullMacrosStr(Options.get("NullMacros", "")) {
+  NullMacrosStr(Options.get("NullMacros", "NULL")) {
   StringRef(NullMacrosStr).split(NullMacros, ",");
 }
 
Index: clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -100,23 +100,6 @@
 "modernize-use-uncaught-exceptions");
 CheckFactories.registerCheck("modernize-use-using");
   }
-
-  ClangTidyOptions getModuleOptions() override {
-ClangTidyOptions Options;
-auto &Opts = Options.CheckOptions;
-// For types whose size in bytes is above this threshold, we prefer taking a
-// const-reference than making a copy.
-Opts["modernize-loop-convert.MaxCopySize"] = "16";
-
-Opts["modernize-loop-convert.MinConfidence"] = "reasonable";
-Opts["modernize-loop-convert.NamingStyle"] = "CamelCase";
-Opts["modernize-pass-by-value.IncludeStyle"] = "llvm";// Also: "google".
-Opts["modernize-replace-auto-ptr.IncludeStyle"] = "llvm"; // Also: "google".
-
-// Comma-separated list of macros that behave like NULL.
-Opts["modernize-use-nullptr.NullMacros"] = "NULL";
-return Options;
-  }
 };
 
 // Register the ModernizeTidyModule using this statically initialized variable.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D143919: [Clang] Copy strictfp attribute from pattern to instantiation

2023-02-15 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff updated this revision to Diff 497609.
sepavloff added a comment.

Changed the way to copy strictfp attribute


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143919

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/CodeGen/fp-template.cpp


Index: clang/test/CodeGen/fp-template.cpp
===
--- /dev/null
+++ clang/test/CodeGen/fp-template.cpp
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm 
-fdelayed-template-parsing -o - %s | FileCheck %s
+
+template 
+T templ_01(T x, T y) {
+#pragma STDC FENV_ACCESS ON
+  return x + y;
+}
+
+float func_01(float x, float y) {
+  return templ_01(x, y);
+}
+
+// CHECK-LABEL: define {{.*}} @_Z8templ_01IfET_S0_S0_
+// CHECK-SAME:  (float noundef %{{.*}}, float noundef %{{.*}}) 
#[[ATTR01:[0-9]+]]{{.*}} {
+// CHECK:   call float @llvm.experimental.constrained.fadd.f32
+
+// CHECK: attributes #[[ATTR01]] = { {{.*}}strictfp
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -606,6 +606,13 @@
   New->addAttr(Attr.clone(S.getASTContext()));
 }
 
+static void instantiateDependentStrictFPAttr(
+Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
+const StrictFPAttr &Attr, Decl *New) {
+  if (!New->hasAttr())
+New->addAttr(Attr.clone(S.getASTContext()));
+}
+
 /// Determine whether the attribute A might be relevant to the declaration D.
 /// If not, we can skip instantiating it. The attribute may or may not have
 /// been instantiated yet.
@@ -811,6 +818,11 @@
   continue;
 }
 
+if (auto *A = dyn_cast(TmplAttr)) {
+  instantiateDependentStrictFPAttr(*this, TemplateArgs, *A, New);
+  continue;
+}
+
 assert(!TmplAttr->isPackExpansion());
 if (TmplAttr->isLateParsed() && LateAttrs) {
   // Late parsed attributes must be instantiated and attached after the
@@ -834,6 +846,22 @@
   }
 }
 
+/// Update instantiation attributes after template was late parsed.
+///
+/// Some attributes are evaluated based on the body of template. If it is
+/// late parsed, such attributes cannot be evaluated when declaration is
+/// instantiated. This function is used to update instantiation attributes when
+/// template definition is ready.
+void Sema::updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst) {
+  for (const auto *TmplAttr : Pattern->attrs()) {
+if (auto *A = dyn_cast(TmplAttr)) {
+  instantiateDependentStrictFPAttr(*this, MultiLevelTemplateArgumentList(),
+   *A, Inst);
+  continue;
+}
+  }
+}
+
 /// In the MS ABI, we need to instantiate default arguments of dllexported
 /// default constructors along with the constructor definition. This allows IR
 /// gen to emit a constructor closure which calls the default constructor with
@@ -4916,6 +4944,7 @@
"missing LateParsedTemplate");
 LateTemplateParser(OpaqueParser, *LPTIter->second);
 Pattern = PatternDecl->getBody(PatternDecl);
+updateAttrsForLateParsedTemplate(PatternDecl, Function);
   }
 
   // Note, we should never try to instantiate a deleted function template.
Index: clang/include/clang/Sema/Sema.h
===
--- clang/include/clang/Sema/Sema.h
+++ clang/include/clang/Sema/Sema.h
@@ -10072,6 +10072,7 @@
 const Decl *Pattern, Decl *Inst,
 LateInstantiatedAttrVec *LateAttrs = nullptr,
 LocalInstantiationScope *OuterMostScope = nullptr);
+  void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
 
   void
   InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,


Index: clang/test/CodeGen/fp-template.cpp
===
--- /dev/null
+++ clang/test/CodeGen/fp-template.cpp
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -fdelayed-template-parsing -o - %s | FileCheck %s
+
+template 
+T templ_01(T x, T y) {
+#pragma STDC FENV_ACCESS ON
+  return x + y;
+}
+
+float func_01(float x, float y) {
+  return templ_01(x, y);
+}
+
+// CHECK-LABEL: define {{.*}} @_Z8templ_01IfET_S0_S0_
+// CHECK-SAME:  (float noundef %{{.*}}, float noundef %{{.*}}) #[[ATTR01:[0-9]+]]{{.*}} {
+// CHECK:   call float @llvm.experimental.constrained.fadd.f32
+
+// CHECK: attributes #[[ATTR01]] = { {{.*}}strictfp
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===

[PATCH] D143919: [Clang] Copy strictfp attribute from pattern to instantiation

2023-02-15 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff added a comment.

In D143919#4123922 , @rjmccall wrote:

> In D143919#4123712 , @sepavloff 
> wrote:
>
>> In D143919#4123616 , @efriedma 
>> wrote:
>>
>>> We have code somewhere to generically copy attributes from function 
>>> templates to instantiations, right?  Why do we need to explicitly copy 
>>> StrictFPAttr in particular, separate from that?
>>
>> Could you please point me out to this code? I didn't find it.
>
> It's the call to `InstantiateAttrs` in `InitFunctionInstantiation`.  
> `InstantiateAttrs` hard-codes a list of attributes to clone, which seems like 
> a bad design, but it's easy enough to add your attribute as another case to 
> that list.

Thanks!
`InstantiateAttrs` is updated accordingly. It solves the problem but not for 
late-parsed templates. Strictfp is evaluated based on function body, but when a 
declaration for late-parsed template is instantiated, the body is absent yet. A 
new method is added to Sema to make attribute update when template body is 
available.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143919

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


[PATCH] D141666: [RISCV] Proper support of extensions Zicsr and Zifencei

2023-02-15 Thread Elena Lepilkina via Phabricator via cfe-commits
eklepilkina updated this revision to Diff 497620.
eklepilkina added a comment.

- [RISCV] Prepare work to be ready for adding separate Zicsr and Zifencei 
extensions
- [RISCV] Proper support of extensions Zicsr and Zifencei
- Updated I extension verson
- Fixing after updating


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141666

Files:
  clang/lib/Driver/ToolChains/Arch/RISCV.cpp
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/test/Driver/baremetal.cpp
  clang/test/Driver/riscv-default-features.c
  clang/test/Driver/riscv-gnutools.c
  llvm/docs/RISCVUsage.rst
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/RISCVFeatures.td
  llvm/lib/Target/RISCV/RISCVISelLowering.cpp
  llvm/lib/Target/RISCV/RISCVInstrInfo.td
  llvm/test/CodeGen/RISCV/attributes.ll
  llvm/test/CodeGen/RISCV/get-register-noreserve.ll
  llvm/test/CodeGen/RISCV/readcyclecounter.ll
  llvm/test/CodeGen/RISCV/rvv/rvv-stack-align.mir
  llvm/test/CodeGen/RISCV/rvv/scalar-stack-align.ll
  llvm/test/CodeGen/RISCV/rvv/vscale-power-of-two.ll
  llvm/test/CodeGen/RISCV/rvv/zvlsseg-zero-vl.ll
  llvm/test/CodeGen/RISCV/vlenb.ll
  llvm/test/MC/RISCV/Ztso.s
  llvm/test/MC/RISCV/csr-aliases.s
  llvm/test/MC/RISCV/deprecated-csr-names.s
  llvm/test/MC/RISCV/hypervisor-csr-names.s
  llvm/test/MC/RISCV/machine-csr-names.s
  llvm/test/MC/RISCV/rv32-hypervisor-csr-names.s
  llvm/test/MC/RISCV/rv32-machine-csr-names.s
  llvm/test/MC/RISCV/rv32-supervisor-csr-names.s
  llvm/test/MC/RISCV/rv32-user-csr-names.s
  llvm/test/MC/RISCV/rv32e-valid.s
  llvm/test/MC/RISCV/rv32i-aliases-valid.s
  llvm/test/MC/RISCV/rv32i-invalid.s
  llvm/test/MC/RISCV/rv32i-valid.s
  llvm/test/MC/RISCV/rv64-machine-csr-names.s
  llvm/test/MC/RISCV/rv64-user-csr-names.s
  llvm/test/MC/RISCV/rvf-user-csr-names.s
  llvm/test/MC/RISCV/rvi-aliases-valid.s
  llvm/test/MC/RISCV/rvk-user-csr-name.s
  llvm/test/MC/RISCV/supervisor-csr-names.s
  llvm/test/MC/RISCV/user-csr-names.s

Index: llvm/test/MC/RISCV/user-csr-names.s
===
--- llvm/test/MC/RISCV/user-csr-names.s
+++ llvm/test/MC/RISCV/user-csr-names.s
@@ -1,13 +1,13 @@
-# RUN: llvm-mc %s -triple=riscv32 -riscv-no-aliases -show-encoding \
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+zicsr -riscv-no-aliases -show-encoding \
 # RUN: | FileCheck -check-prefixes=CHECK-INST,CHECK-ENC %s
-# RUN: llvm-mc -filetype=obj -triple riscv32 < %s \
-# RUN: | llvm-objdump -d - \
+# RUN: llvm-mc -filetype=obj -triple riscv32 -mattr=+zicsr < %s \
+# RUN: | llvm-objdump -d --mattr=+zicsr - \
 # RUN: | FileCheck -check-prefix=CHECK-INST-ALIAS %s
 #
-# RUN: llvm-mc %s -triple=riscv64 -riscv-no-aliases -show-encoding \
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+zicsr -riscv-no-aliases -show-encoding \
 # RUN: | FileCheck -check-prefixes=CHECK-INST,CHECK-ENC %s
-# RUN: llvm-mc -filetype=obj -triple riscv64 < %s \
-# RUN: | llvm-objdump -d - \
+# RUN: llvm-mc -filetype=obj -triple riscv64 -mattr=+zicsr < %s \
+# RUN: | llvm-objdump -d --mattr=+zicsr - \
 # RUN: | FileCheck -check-prefix=CHECK-INST-ALIAS %s
 
 ##
Index: llvm/test/MC/RISCV/supervisor-csr-names.s
===
--- llvm/test/MC/RISCV/supervisor-csr-names.s
+++ llvm/test/MC/RISCV/supervisor-csr-names.s
@@ -1,13 +1,13 @@
-# RUN: llvm-mc %s -triple=riscv32 -riscv-no-aliases -show-encoding \
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+zicsr -riscv-no-aliases -show-encoding \
 # RUN: | FileCheck -check-prefixes=CHECK-INST,CHECK-ENC %s
-# RUN: llvm-mc -filetype=obj -triple riscv32 < %s \
-# RUN: | llvm-objdump -d - \
+# RUN: llvm-mc -filetype=obj -triple riscv32 -mattr=+zicsr < %s \
+# RUN: | llvm-objdump -d --mattr=+zicsr - \
 # RUN: | FileCheck -check-prefix=CHECK-INST-ALIAS %s
 #
-# RUN: llvm-mc %s -triple=riscv64 -riscv-no-aliases -show-encoding \
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+zicsr -riscv-no-aliases -show-encoding \
 # RUN: | FileCheck -check-prefixes=CHECK-INST,CHECK-ENC %s
-# RUN: llvm-mc -filetype=obj -triple riscv64 < %s \
-# RUN: | llvm-objdump -d - \
+# RUN: llvm-mc -filetype=obj -triple riscv64 -mattr=+zicsr < %s \
+# RUN: | llvm-objdump -d --mattr=+zicsr - \
 # RUN: | FileCheck -check-prefix=CHECK-INST-ALIAS %s
 
 ##
Index: llvm/test/MC/RISCV/rvk-user-csr-name.s
===
--- llvm/test/MC/RISCV/rvk-user-csr-name.s
+++ llvm/test/MC/RISCV/rvk-user-csr-name.s
@@ -1,13 +1,13 @@
-# RUN: llvm-mc %s -triple=riscv32 -riscv-no-aliases -mattr=+f -show-encoding \
+# RUN: llvm-mc %s -triple=riscv32 -riscv-no-aliases -mattr=+zicsr,+f -show-encoding \
 # RUN: | FileCheck -check-prefixes=CHECK-INST,CHECK-ENC %s
-# RUN: llvm-mc -filetype=obj -triple riscv32 -mattr=

[clang] 5bb8ead - [AArch64][NFC] Rename AEK_SMEF64 and AEK_SMEI64 feature flags

2023-02-15 Thread Caroline Concatto via cfe-commits

Author: Caroline Concatto
Date: 2023-02-15T11:39:00Z
New Revision: 5bb8ead4e9dc4a03bddae1f7d3419e97eac37426

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

LOG: [AArch64][NFC] Rename  AEK_SMEF64 and AEK_SMEI64 feature flags

Update feature flag names from:
AEK_SMEF64  to AEK_SMEF64F64
and
AEK_SMEI64 to AEK_SMEI16I64
These feature flags had their name changed in this previous patch
 https://reviews.llvm.org/D135974

Reviewed By: c-rhodes

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

Added: 


Modified: 
clang/lib/Basic/Targets/AArch64.cpp
clang/lib/Basic/Targets/AArch64.h

Removed: 




diff  --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index a0eae3177e3ab..9b67becff9e75 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -663,8 +663,8 @@ bool AArch64TargetInfo::hasFeature(StringRef Feature) const 
{
   .Case("sve2-sha3", FPU & SveMode && HasSVE2SHA3)
   .Case("sve2-sm4", FPU & SveMode && HasSVE2SM4)
   .Case("sme", HasSME)
-  .Case("sme-f64f64", HasSMEF64)
-  .Case("sme-i16i64", HasSMEI64)
+  .Case("sme-f64f64", HasSMEF64F64)
+  .Case("sme-i16i64", HasSMEI16I64)
   .Cases("memtag", "memtag2", HasMTE)
   .Case("sb", HasSB)
   .Case("predres", HasPredRes)
@@ -780,12 +780,12 @@ bool 
AArch64TargetInfo::handleTargetFeatures(std::vector &Features,
 }
 if (Feature == "+sme-f64f64") {
   HasSME = true;
-  HasSMEF64 = true;
+  HasSMEF64F64 = true;
   HasBFloat16 = true;
 }
 if (Feature == "+sme-i16i64") {
   HasSME = true;
-  HasSMEI64 = true;
+  HasSMEI16I64 = true;
   HasBFloat16 = true;
 }
 if (Feature == "+sb")

diff  --git a/clang/lib/Basic/Targets/AArch64.h 
b/clang/lib/Basic/Targets/AArch64.h
index 23cabc5885104..46bfb70a0d953 100644
--- a/clang/lib/Basic/Targets/AArch64.h
+++ b/clang/lib/Basic/Targets/AArch64.h
@@ -64,8 +64,8 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public 
TargetInfo {
   bool HasCCDP = false;
   bool HasFRInt3264 = false;
   bool HasSME = false;
-  bool HasSMEF64 = false;
-  bool HasSMEI64 = false;
+  bool HasSMEF64F64 = false;
+  bool HasSMEI16I64 = false;
   bool HasSB = false;
   bool HasPredRes = false;
   bool HasSSBS = false;



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


[PATCH] D143989: [AArch64][NFC] Rename AEK_SMEF64 and AEK_SMEI64 feature flags

2023-02-15 Thread Caroline 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 rG5bb8ead4e9dc: [AArch64][NFC] Rename  AEK_SMEF64 and 
AEK_SMEI64 feature flags (authored by CarolineConcatto).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143989

Files:
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Basic/Targets/AArch64.h


Index: clang/lib/Basic/Targets/AArch64.h
===
--- clang/lib/Basic/Targets/AArch64.h
+++ clang/lib/Basic/Targets/AArch64.h
@@ -64,8 +64,8 @@
   bool HasCCDP = false;
   bool HasFRInt3264 = false;
   bool HasSME = false;
-  bool HasSMEF64 = false;
-  bool HasSMEI64 = false;
+  bool HasSMEF64F64 = false;
+  bool HasSMEI16I64 = false;
   bool HasSB = false;
   bool HasPredRes = false;
   bool HasSSBS = false;
Index: clang/lib/Basic/Targets/AArch64.cpp
===
--- clang/lib/Basic/Targets/AArch64.cpp
+++ clang/lib/Basic/Targets/AArch64.cpp
@@ -663,8 +663,8 @@
   .Case("sve2-sha3", FPU & SveMode && HasSVE2SHA3)
   .Case("sve2-sm4", FPU & SveMode && HasSVE2SM4)
   .Case("sme", HasSME)
-  .Case("sme-f64f64", HasSMEF64)
-  .Case("sme-i16i64", HasSMEI64)
+  .Case("sme-f64f64", HasSMEF64F64)
+  .Case("sme-i16i64", HasSMEI16I64)
   .Cases("memtag", "memtag2", HasMTE)
   .Case("sb", HasSB)
   .Case("predres", HasPredRes)
@@ -780,12 +780,12 @@
 }
 if (Feature == "+sme-f64f64") {
   HasSME = true;
-  HasSMEF64 = true;
+  HasSMEF64F64 = true;
   HasBFloat16 = true;
 }
 if (Feature == "+sme-i16i64") {
   HasSME = true;
-  HasSMEI64 = true;
+  HasSMEI16I64 = true;
   HasBFloat16 = true;
 }
 if (Feature == "+sb")


Index: clang/lib/Basic/Targets/AArch64.h
===
--- clang/lib/Basic/Targets/AArch64.h
+++ clang/lib/Basic/Targets/AArch64.h
@@ -64,8 +64,8 @@
   bool HasCCDP = false;
   bool HasFRInt3264 = false;
   bool HasSME = false;
-  bool HasSMEF64 = false;
-  bool HasSMEI64 = false;
+  bool HasSMEF64F64 = false;
+  bool HasSMEI16I64 = false;
   bool HasSB = false;
   bool HasPredRes = false;
   bool HasSSBS = false;
Index: clang/lib/Basic/Targets/AArch64.cpp
===
--- clang/lib/Basic/Targets/AArch64.cpp
+++ clang/lib/Basic/Targets/AArch64.cpp
@@ -663,8 +663,8 @@
   .Case("sve2-sha3", FPU & SveMode && HasSVE2SHA3)
   .Case("sve2-sm4", FPU & SveMode && HasSVE2SM4)
   .Case("sme", HasSME)
-  .Case("sme-f64f64", HasSMEF64)
-  .Case("sme-i16i64", HasSMEI64)
+  .Case("sme-f64f64", HasSMEF64F64)
+  .Case("sme-i16i64", HasSMEI16I64)
   .Cases("memtag", "memtag2", HasMTE)
   .Case("sb", HasSB)
   .Case("predres", HasPredRes)
@@ -780,12 +780,12 @@
 }
 if (Feature == "+sme-f64f64") {
   HasSME = true;
-  HasSMEF64 = true;
+  HasSMEF64F64 = true;
   HasBFloat16 = true;
 }
 if (Feature == "+sme-i16i64") {
   HasSME = true;
-  HasSMEI64 = true;
+  HasSMEI16I64 = true;
   HasBFloat16 = true;
 }
 if (Feature == "+sb")
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D140756: Add clang_CXXMethod_isExplicit to libclang

2023-02-15 Thread Luca Di sera via Phabricator via cfe-commits
diseraluca added a comment.

In D140756#4100387 , @aaron.ballman 
wrote:

> @diseraluca -- do you need this cherry picked into Clang 16 or are you fine 
> if this goes into Clang 17 instead?

Sorry for checking in so late, I noticed the notifications only now. We are 
using a different solution for the time being so it is correct that this is 
fine being in Clang 17.

Thank you for taking care of this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140756

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


[PATCH] D122215: [WebAssembly] Initial support for reference type externref in clang

2023-02-15 Thread Paulo Matos via Phabricator via cfe-commits
pmatos updated this revision to Diff 497630.
pmatos added a comment.

Rebased against HEAD. Waiting for @vitalybuka go ahead to land.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122215

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/Type.h
  clang/include/clang/AST/TypeProperties.td
  clang/include/clang/Basic/BuiltinsWebAssembly.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/WebAssemblyReferenceTypes.def
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/include/clang/module.modulemap
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/MicrosoftMangle.cpp
  clang/lib/AST/NSAPI.cpp
  clang/lib/AST/PrintfFormatString.cpp
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypeLoc.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/lib/CodeGen/CodeGenTypes.cpp
  clang/lib/CodeGen/ItaniumCXXABI.cpp
  clang/lib/CodeGen/TargetInfo.cpp
  clang/lib/CodeGen/TargetInfo.h
  clang/lib/Index/USRGeneration.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaType.cpp
  clang/lib/Serialization/ASTCommon.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/test/CodeGen/WebAssembly/wasm-externref.c
  clang/test/CodeGen/builtins-wasm.c
  clang/test/CodeGenCXX/wasm-reftypes-mangle.cpp
  clang/test/CodeGenCXX/wasm-reftypes-typeinfo.cpp
  clang/test/Sema/wasm-refs.c
  clang/test/SemaCXX/wasm-refs.cpp
  clang/test/SemaTemplate/address_space-dependent.cpp
  clang/tools/libclang/CIndex.cpp
  llvm/include/llvm/IR/Type.h
  llvm/include/llvm/Transforms/Utils.h
  llvm/lib/CodeGen/ValueTypes.cpp
  llvm/lib/IR/Type.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
  llvm/lib/Transforms/Utils/Mem2Reg.cpp

Index: llvm/lib/Transforms/Utils/Mem2Reg.cpp
===
--- llvm/lib/Transforms/Utils/Mem2Reg.cpp
+++ llvm/lib/Transforms/Utils/Mem2Reg.cpp
@@ -74,15 +74,19 @@
 struct PromoteLegacyPass : public FunctionPass {
   // Pass identification, replacement for typeid
   static char ID;
+  bool ForcePass; /// If true, forces pass to execute, instead of skipping.
 
-  PromoteLegacyPass() : FunctionPass(ID) {
+  PromoteLegacyPass() : FunctionPass(ID), ForcePass(false) {
+initializePromoteLegacyPassPass(*PassRegistry::getPassRegistry());
+  }
+  PromoteLegacyPass(bool IsForced) : FunctionPass(ID), ForcePass(IsForced) {
 initializePromoteLegacyPassPass(*PassRegistry::getPassRegistry());
   }
 
   // runOnFunction - To run this pass, first we calculate the alloca
   // instructions that are safe for promotion, then we promote each one.
   bool runOnFunction(Function &F) override {
-if (skipFunction(F))
+if (!ForcePass && skipFunction(F))
   return false;
 
 DominatorTree &DT = getAnalysis().getDomTree();
@@ -96,6 +100,7 @@
 AU.addRequired();
 AU.setPreservesCFG();
   }
+
 };
 
 } // end anonymous namespace
@@ -111,6 +116,6 @@
 false, false)
 
 // createPromoteMemoryToRegister - Provide an entry point to create this pass.
-FunctionPass *llvm::createPromoteMemoryToRegisterPass() {
-  return new PromoteLegacyPass();
+FunctionPass *llvm::createPromoteMemoryToRegisterPass(bool IsForced) {
+  return new PromoteLegacyPass(IsForced);
 }
Index: llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
===
--- llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
+++ llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
@@ -16,6 +16,7 @@
 #include "TargetInfo/WebAssemblyTargetInfo.h"
 #include "Utils/WebAssemblyUtilities.h"
 #include "WebAssembly.h"
+#include "WebAssemblyISelLowering.h"
 #include "WebAssemblyMachineFunctionInfo.h"
 #include "WebAssemblyTargetObjectFile.h"
 #include "WebAssemblyTargetTransformInfo.h"
@@ -464,6 +465,14 @@
 }
 
 void WebAssemblyPassConfig::addISelPrepare() {
+  WebAssemblyTargetMachine *WasmTM = static_cast(TM);
+  const WebAssemblySubtarget *Subtarget = WasmTM
+->getSubtargetImpl(std::string(WasmTM->getTargetCPU()),
+   std::string(WasmTM->getTargetFeatureString()));
+  if(Subtarget->hasReferenceTypes()) {
+// We need to remove allocas for reference types
+addPass(createPromoteMemoryToRegisterPass(true));
+  }
   // Lower atomics and TLS if necessary
   addPass(new CoalesceFeaturesAndStripAtomics(&getWebAssemblyTargetMachine()));
 
Index: llvm/lib/IR/Type.cpp
===
--- llvm/lib/IR/Type.cpp
+++ llvm/lib/IR/Type.cpp
@@ -306,6 +306,18 @@
   return getInt64Ty(C)->getPointerTo(AS);
 }
 
+Type *Type::getWasm_Externr

[PATCH] D128440: [WebAssembly] Initial support for reference type funcref in clang

2023-02-15 Thread Paulo Matos via Phabricator via cfe-commits
pmatos updated this revision to Diff 497632.
pmatos added a comment.

Rebased on current HEAD.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128440

Files:
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/AST/Type.h
  clang/include/clang/Basic/AddressSpaces.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/BuiltinsWebAssembly.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/DeclBase.cpp
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/Basic/Targets/DirectX.h
  clang/lib/Basic/Targets/NVPTX.h
  clang/lib/Basic/Targets/SPIR.h
  clang/lib/Basic/Targets/TCE.h
  clang/lib/Basic/Targets/WebAssembly.h
  clang/lib/Basic/Targets/X86.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/TargetInfo.cpp
  clang/lib/CodeGen/TargetInfo.h
  clang/lib/Format/FormatToken.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseTentative.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/CodeGen/WebAssembly/wasm-funcref.c
  clang/test/Parser/wasm-funcref.c
  clang/test/Sema/wasm-refs.c
  clang/test/SemaTemplate/address_space-dependent.cpp

Index: clang/test/SemaTemplate/address_space-dependent.cpp
===
--- clang/test/SemaTemplate/address_space-dependent.cpp
+++ clang/test/SemaTemplate/address_space-dependent.cpp
@@ -43,7 +43,7 @@
 
 template 
 void tooBig() {
-  __attribute__((address_space(I))) int *bounds; // expected-error {{address space is larger than the maximum supported (8388587)}}
+  __attribute__((address_space(I))) int *bounds; // expected-error {{address space is larger than the maximum supported (8388586)}}
 }
 
 template 
@@ -101,7 +101,7 @@
   car<1, 2, 3>(); // expected-note {{in instantiation of function template specialization 'car<1, 2, 3>' requested here}}
   HasASTemplateFields<1> HASTF;
   neg<-1>(); // expected-note {{in instantiation of function template specialization 'neg<-1>' requested here}}
-  correct<0x7FFFEA>();
+  correct<0x7FFFE9>();
   tooBig<8388650>(); // expected-note {{in instantiation of function template specialization 'tooBig<8388650L>' requested here}}
 
   __attribute__((address_space(1))) char *x;
Index: clang/test/Sema/wasm-refs.c
===
--- clang/test/Sema/wasm-refs.c
+++ clang/test/Sema/wasm-refs.c
@@ -46,6 +46,8 @@
 __externref_t ***illegal_return_2(); // expected-error {{pointer to WebAssembly reference type is not allowed}}
 
 void varargs(int, ...);
+typedef void (*__funcref funcref_t)();
+typedef void (*__funcref __funcref funcref_fail_t)(); // expected-warning {{attribute '__funcref' is already applied}}
 
 __externref_t func(__externref_t ref) {
   &ref; // expected-error {{cannot take address of WebAssembly reference}}
@@ -67,5 +69,7 @@
   _Alignof(__externref_t ***);   // expected-error {{pointer to WebAssembly reference type is not allowed}};
   varargs(1, ref);   // expected-error {{cannot pass expression of type '__externref_t' to variadic function}}
 
+  funcref_t func = __builtin_wasm_ref_null_func(0); // expected-error {{too many arguments to function call, expected 0, have 1}}
+
   return ref;
 }
Index: clang/test/Parser/wasm-funcref.c
===
--- /dev/null
+++ clang/test/Parser/wasm-funcref.c
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -triple powerpc-linux-gnu -fsyntax-only -verify %s
+
+// Test that we trigger an error at parse time if using keyword funcref
+// while not using a wasm triple.
+typedef void (*__funcref funcref_t)(); // expected-error {{invalid use of '__funcref' keyword outside the WebAssembly triple}}
+typedef int (*__funcref fn_funcref_t)(int);// expected-error {{invalid use of '__funcref' keyword outside the WebAssembly triple}}
+typedef int (*fn_t)(int);
+
+static fn_funcref_t nullFuncref = 0;
Index: clang/test/CodeGen/WebAssembly/wasm-funcref.c
===
--- /dev/null
+++ clang/test/CodeGen/WebAssembly/wasm-funcref.c
@@ -0,0 +1,99 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -triple wasm32 -target-feature +reference-types -o - -emit-llvm %s | FileCheck %s
+
+typedef void (*__funcref funcref_t)();
+typedef int (*__funcref fn_funcref_t)(int);
+typedef int (*fn_t)(int);
+
+// Null funcref builtin call
+// CHECK-LABEL: @get_null(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = call ptr addrspace(20) @llvm.wasm.ref.null.func()
+// CHECK-NEXT:ret ptr addrspace(20) [[TMP0]]
+//
+funcref_t get_null() {
+  return __builtin_wasm_ref_null

[PATCH] D139010: [clang][WebAssembly] Implement support for table types and builtins

2023-02-15 Thread Paulo Matos via Phabricator via cfe-commits
pmatos updated this revision to Diff 497633.
pmatos added a comment.

Rebased on current HEAD.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139010

Files:
  clang/include/clang/AST/Expr.h
  clang/include/clang/AST/Stmt.h
  clang/include/clang/AST/Type.h
  clang/include/clang/Basic/BuiltinsWebAssembly.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/Specifiers.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/include/clang/Serialization/TypeBitCodes.def
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/AST/Type.cpp
  clang/lib/Basic/Targets/WebAssembly.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGValue.h
  clang/lib/Sema/SemaCast.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExceptionSpec.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/CodeGen/WebAssembly/builtins-table.c
  clang/test/CodeGen/WebAssembly/table.c
  clang/test/Sema/builtins-wasm.c
  clang/test/Sema/wasm-refs.c
  clang/test/SemaCXX/wasm-refs-and-tables.cpp
  clang/test/SemaCXX/wasm-refs.cpp
  llvm/include/llvm/CodeGen/WasmAddressSpaces.h
  llvm/include/llvm/IR/Type.h
  llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.cpp
  llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.h
  llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyLowerRefTypesIntPtrConv.cpp

Index: llvm/lib/Target/WebAssembly/WebAssemblyLowerRefTypesIntPtrConv.cpp
===
--- llvm/lib/Target/WebAssembly/WebAssemblyLowerRefTypesIntPtrConv.cpp
+++ llvm/lib/Target/WebAssembly/WebAssemblyLowerRefTypesIntPtrConv.cpp
@@ -62,8 +62,9 @@
   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
 PtrToIntInst *PTI = dyn_cast(&*I);
 IntToPtrInst *ITP = dyn_cast(&*I);
-if (!(PTI && WebAssembly::isRefType(PTI->getPointerOperand()->getType())) &&
-!(ITP && WebAssembly::isRefType(ITP->getDestTy(
+if (!(PTI &&
+  PTI->getPointerOperand()->getType()->isWebAssemblyReferenceType()) &&
+!(ITP && ITP->getDestTy()->isWebAssemblyReferenceType()))
   continue;
 
 UndefValue *U = UndefValue::get(I->getType());
Index: llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
===
--- llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
+++ llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
@@ -1202,7 +1202,7 @@
   // Lastly, if this is a call to a funcref we need to add an instruction
   // table.set to the chain and transform the call.
   if (CLI.CB &&
-  WebAssembly::isFuncrefType(CLI.CB->getCalledOperand()->getType())) {
+  CLI.CB->getCalledOperand()->getType()->isWebAssemblyFuncrefType()) {
 // In the absence of function references proposal where a funcref call is
 // lowered to call_ref, using reference types we generate a table.set to set
 // the funcref to a special table used solely for this purpose, followed by
Index: llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.h
===
--- llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.h
+++ llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.h
@@ -45,43 +45,6 @@
   Multivalue = 0x,
 };
 
-enum WasmAddressSpace : unsigned {
-  // Default address space, for pointers to linear memory (stack, heap, data).
-  WASM_ADDRESS_SPACE_DEFAULT = 0,
-  // A non-integral address space for pointers to named objects outside of
-  // linear memory: WebAssembly globals or WebAssembly locals.  Loads and stores
-  // to these pointers are lowered to global.get / global.set or local.get /
-  // local.set, as appropriate.
-  WASM_ADDRESS_SPACE_VAR = 1,
-  // A non-integral address space for externref values
-  WASM_ADDRESS_SPACE_EXTERNREF = 10,
-  // A non-integral address space for funcref values
-  WASM_ADDRESS_SPACE_FUNCREF = 20,
-};
-
-inline bool isDefaultAddressSpace(unsigned AS) {
-  return AS == WASM_ADDRESS_SPACE_DEFAULT;
-}
-inline bool isWasmVarAddressSpace(unsigned AS) {
-  return AS == WASM_ADDRESS_SPACE_VAR;
-}
-inline bool isValidAddressSpace(unsigned AS) {
-  return isDefaultAddressSpace(AS) || isWasmVarAddressSpace(AS);
-}
-inline bool isFuncrefType(const Type *Ty) {
-  return isa(Ty) &&
- Ty->getPointerAddressSpace() ==
- WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF;
-}
-inline bool isExternrefType(const Type *Ty) {
-  return isa(Ty) &&
- Ty->getPointerAddressSpace() ==
- WasmAddressSpace::WASM_ADDRESS_SPACE_EXTERNREF;
-}
-inline bool isRefType(const 

Re: [clang] d05e1e9 - [clang][test][RISCV] Check for __riscv_i in riscv-target-features.c

2023-02-15 Thread Alex Bradbury via cfe-commits
Addressed in ddb704247b16002d916bba67e3aa9f54fd4bbace - thanks again.

Best,

Alex

On 2023-02-14 20:58, Craig Topper wrote:
> I don't have a better idea.
> 
> ~Craig
> 
> On Tue, Feb 14, 2023 at 12:32 PM Alex Bradbury  wrote:
> 
>> On 2023-02-14 19:56, Craig Topper wrote:
>>> How does this interact with the CHECK-NOTs above it. Does it check
>>> that they don't appear before the __riscv_i but would be allowed
>> after
>>> it?
>>
>> Thanks for the post-commit review. I think you're right.
>>
>> It looks like the easiest fix is probably move the __riscv_i check
>> out
>> of that block of CHECK-NOTs and just add a new:
>>
>> // RUN: %clang -target riscv32-unknown-linux-gnu -march=rv32i -x c
>> -E
>> -dM %s \
>> // RUN: -o - | FileCheck %s
>> // RUN: %clang -target riscv64-unknown-linux-gnu -march=rv64i -x c
>> -E
>> -dM %s \
>> // RUN: -o - | FileCheck %s
>> // CHECK: __riscv_i 200{{$}}
>>
>> Do you agree, or am I missing a better alternative?
>>
>> Cheers,
>>
>> Alex
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 7cbbbc0 - clang: Rename misleading test name

2023-02-15 Thread Matt Arsenault via cfe-commits

Author: Matt Arsenault
Date: 2023-02-15T08:32:57-04:00
New Revision: 7cbbbc0a045bf1597972dabd2e071786157c87bf

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

LOG: clang: Rename misleading test name

This is a test for attribute propagation, not metadata

Added: 
clang/test/CodeGenCUDA/propagate-attributes.cu

Modified: 


Removed: 
clang/test/CodeGenCUDA/propagate-metadata.cu



diff  --git a/clang/test/CodeGenCUDA/propagate-metadata.cu 
b/clang/test/CodeGenCUDA/propagate-attributes.cu
similarity index 100%
rename from clang/test/CodeGenCUDA/propagate-metadata.cu
rename to clang/test/CodeGenCUDA/propagate-attributes.cu



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


[PATCH] D143070: [clang-format] Enable FormatTokenSource to insert tokens.

2023-02-15 Thread Manuel Klimek via Phabricator via cfe-commits
klimek updated this revision to Diff 497637.
klimek marked an inline comment as done.
klimek added a comment.

Address review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143070

Files:
  clang/lib/Format/FormatTokenSource.h
  clang/lib/Format/UnwrappedLineParser.h
  clang/unittests/Format/FormatTokenSourceTest.cpp

Index: clang/unittests/Format/FormatTokenSourceTest.cpp
===
--- clang/unittests/Format/FormatTokenSourceTest.cpp
+++ clang/unittests/Format/FormatTokenSourceTest.cpp
@@ -28,12 +28,17 @@
 #define EXPECT_TOKEN_KIND(FormatTok, Kind) \
   do { \
 FormatToken *Tok = FormatTok;  \
-EXPECT_EQ((Tok)->Tok.getKind(), Kind) << *(Tok);   \
+EXPECT_EQ(Tok->Tok.getKind(), Kind) << *Tok;   \
+  } while (false);
+#define EXPECT_TOKEN_ID(FormatTok, Name)   \
+  do { \
+FormatToken *Tok = FormatTok;  \
+EXPECT_EQ(Tok->Tok.getKind(), tok::identifier) << *Tok;\
+EXPECT_EQ(Tok->TokenText, Name) << *Tok;   \
   } while (false);
 
 TEST_F(IndexedTokenSourceTest, EmptyInput) {
-  TokenList Tokens = lex("");
-  IndexedTokenSource Source(Tokens);
+  IndexedTokenSource Source(lex(""));
   EXPECT_FALSE(Source.isEOF());
   EXPECT_TOKEN_KIND(Source.getNextToken(), tok::eof);
   EXPECT_TRUE(Source.isEOF());
@@ -46,8 +51,7 @@
 }
 
 TEST_F(IndexedTokenSourceTest, NavigateTokenStream) {
-  TokenList Tokens = lex("int a;");
-  IndexedTokenSource Source(Tokens);
+  IndexedTokenSource Source(lex("int a;"));
   EXPECT_TOKEN_KIND(Source.peekNextToken(), tok::kw_int);
   EXPECT_TOKEN_KIND(Source.getNextToken(), tok::kw_int);
   EXPECT_EQ(Source.getPreviousToken(), nullptr);
@@ -60,11 +64,12 @@
   EXPECT_TOKEN_KIND(Source.peekNextToken(), tok::eof);
   EXPECT_TOKEN_KIND(Source.getNextToken(), tok::eof);
   EXPECT_TOKEN_KIND(Source.getPreviousToken(), tok::semi);
+  EXPECT_TOKEN_KIND(Source.getNextToken(), tok::eof);
+  EXPECT_TOKEN_KIND(Source.getPreviousToken(), tok::semi);
 }
 
 TEST_F(IndexedTokenSourceTest, ResetPosition) {
-  TokenList Tokens = lex("int a;");
-  IndexedTokenSource Source(Tokens);
+  IndexedTokenSource Source(lex("int a;"));
   Source.getNextToken();
   unsigned Position = Source.getPosition();
   Source.getNextToken();
@@ -73,6 +78,50 @@
   EXPECT_TOKEN_KIND(Source.setPosition(Position), tok::kw_int);
 }
 
+TEST_F(IndexedTokenSourceTest, InsertTokens) {
+  IndexedTokenSource Source(lex("A1 A2"));
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("B1 B2")), "B1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "B2");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A2");
+}
+
+TEST_F(IndexedTokenSourceTest, InsertTokensAtEOF) {
+  IndexedTokenSource Source(lex("A1"));
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_KIND(Source.getNextToken(), tok::eof);
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("B1 B2")), "B1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "B2");
+  EXPECT_TOKEN_KIND(Source.getNextToken(), tok::eof);
+}
+
+TEST_F(IndexedTokenSourceTest, InsertTokensRecursive) {
+  IndexedTokenSource Source(lex("A1"));
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  // A1
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("B1")), "B1");
+  // B1 A1
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("C1")), "C1");
+  // C1 B1 A1
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("D1")), "D1");
+  // D1 C1 B1 A1
+  EXPECT_TOKEN_ID(Source.getNextToken(), "C1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "B1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+}
+
+TEST_F(IndexedTokenSourceTest, InsertTokensRecursiveAtEndOfSequence) {
+  IndexedTokenSource Source(lex("A1"));
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("B1")), "B1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("C1")), "C1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("D1")), "D1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/UnwrappedLineParser.h
===
--- clang/lib/Format/UnwrappedLineParser.h
+++ clang/lib/Format/UnwrappedLineParser.h
@@ -280,9 +280,6 @@
   FormatTokenSource *Tokens;
   UnwrappedLineConsumer &Callback;
 
-  // FIXME: This is a temporary measure until we have reworked the ownership
-

[PATCH] D143070: [clang-format] Enable FormatTokenSource to insert tokens.

2023-02-15 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.h:287
   // owned outside of and handed into the UnwrappedLineParser.
+  // FIXME: The above fixme doesn't work if we need to create tokens while
+  // parsing.

sammccall wrote:
> I'm not really sure how to read the combination of these two FIXMEs... does 
> it mean "we wanted to do this differently one day, but now we never can"?
> 
> Maybe either delete both, or if you think it's still potentially actionable, 
> something like FIXME: it would be better to have tokens created and owned 
> outside because XYZ, but it's hard because macro expansion mutates the stream
> 
> (I don't really understand what the prev comment is about: the tokens *are* 
> handed into the UnwrappedLineParser constructor. So I may be off base here)
Yeah, I think I don't fully understand what I wanted to fix, so deleted both.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143070

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


[clang] 1995d44 - [clang-format] Enable FormatTokenSource to insert tokens.

2023-02-15 Thread Manuel Klimek via cfe-commits

Author: Manuel Klimek
Date: 2023-02-15T12:39:24Z
New Revision: 1995d4424505cb5a1c3f0e5f851a660ec32d7af1

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

LOG: [clang-format] Enable FormatTokenSource to insert tokens.

In preparation for configured macro replacements in formatting,
add the ability to insert tokens to FormatTokenSource, and implement
token insertion in IndexedTokenSource.

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

Added: 


Modified: 
clang/lib/Format/FormatTokenSource.h
clang/lib/Format/UnwrappedLineParser.h
clang/unittests/Format/FormatTokenSourceTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatTokenSource.h 
b/clang/lib/Format/FormatTokenSource.h
index 0bef45a7ff980..8bf7e6932c895 100644
--- a/clang/lib/Format/FormatTokenSource.h
+++ b/clang/lib/Format/FormatTokenSource.h
@@ -1,4 +1,3 @@
-
 //===--- FormatTokenSource.h - Format C++ code --*- C++ 
-*-===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
@@ -8,7 +7,7 @@
 
//===--===//
 ///
 /// \file
-/// This file defines the \c TokenSource interface, which provides a token
+/// This file defines the \c FormatTokenSource interface, which provides a 
token
 /// stream as well as the ability to manipulate the token stream.
 ///
 
//===--===//
@@ -18,12 +17,17 @@
 
 #include "FormatToken.h"
 #include "UnwrappedLineParser.h"
+#include "llvm/ADT/DenseMap.h"
 
 #define DEBUG_TYPE "format-token-source"
 
 namespace clang {
 namespace format {
 
+// Navigate a token stream.
+//
+// Enables traversal of a token stream, resetting the position in a token
+// stream, as well as inserting new tokens.
 class FormatTokenSource {
 public:
   virtual ~FormatTokenSource() {}
@@ -33,6 +37,9 @@ class FormatTokenSource {
 
   // Returns the token preceding the token returned by the last call to
   // getNextToken() in the token stream, or nullptr if no such token exists.
+  //
+  // Must not be called directly at the position directly after insertTokens()
+  // is called.
   virtual FormatToken *getPreviousToken() = 0;
 
   // Returns the token that would be returned by the next call to
@@ -45,14 +52,31 @@ class FormatTokenSource {
   virtual bool isEOF() = 0;
 
   // Gets the current position in the token stream, to be used by 
setPosition().
+  //
+  // Note that the value of the position is not meaningful, and specifically
+  // should not be used to get relative token positions.
   virtual unsigned getPosition() = 0;
 
   // Resets the token stream to the state it was in when getPosition() returned
   // Position, and return the token at that position in the stream.
   virtual FormatToken *setPosition(unsigned Position) = 0;
+
+  // Insert the given tokens before the current position.
+  // Returns the first token in \c Tokens.
+  // The next returned token will be the second token in \c Tokens.
+  // Requires the last token in Tokens to be EOF; once the EOF token is 
reached,
+  // the next token will be the last token returned by getNextToken();
+  //
+  // For example, given the token sequence 'a1 a2':
+  // getNextToken() -> a1
+  // insertTokens('b1 b2') -> b1
+  // getNextToken() -> b2
+  // getNextToken() -> a1
+  // getNextToken() -> a2
+  virtual FormatToken *insertTokens(ArrayRef Tokens) = 0;
 };
 
-class LLVM_GSL_POINTER IndexedTokenSource : public FormatTokenSource {
+class IndexedTokenSource : public FormatTokenSource {
 public:
   IndexedTokenSource(ArrayRef Tokens)
   : Tokens(Tokens), Position(-1) {}
@@ -65,7 +89,7 @@ class LLVM_GSL_POINTER IndexedTokenSource : public 
FormatTokenSource {
   });
   return Tokens[Position];
 }
-++Position;
+Position = successor(Position);
 LLVM_DEBUG({
   llvm::dbgs() << "Next ";
   dbgToken(Position);
@@ -74,16 +98,17 @@ class LLVM_GSL_POINTER IndexedTokenSource : public 
FormatTokenSource {
   }
 
   FormatToken *getPreviousToken() override {
+assert(Position <= 0 || !Tokens[Position - 1]->is(tok::eof));
 return Position > 0 ? Tokens[Position - 1] : nullptr;
   }
 
   FormatToken *peekNextToken(bool SkipComment = false) override {
 if (isEOF())
   return Tokens[Position];
-int Next = Position + 1;
+int Next = successor(Position);
 if (SkipComment)
   while (Tokens[Next]->is(tok::comment))
-++Next;
+Next = successor(Next);
 LLVM_DEBUG({
   llvm::dbgs() << "Peeking ";
   dbgToken(Next);
@@ -107,9 +132,40 @@ class LLVM_GSL_POINTER IndexedTokenSource : public 
FormatTokenSource {
 return Tokens[Position];
   }
 
+  FormatToken *insertTokens(ArrayRef New) overrid

[PATCH] D143070: [clang-format] Enable FormatTokenSource to insert tokens.

2023-02-15 Thread Manuel Klimek 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 rG1995d4424505: [clang-format] Enable FormatTokenSource to 
insert tokens. (authored by klimek).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143070

Files:
  clang/lib/Format/FormatTokenSource.h
  clang/lib/Format/UnwrappedLineParser.h
  clang/unittests/Format/FormatTokenSourceTest.cpp

Index: clang/unittests/Format/FormatTokenSourceTest.cpp
===
--- clang/unittests/Format/FormatTokenSourceTest.cpp
+++ clang/unittests/Format/FormatTokenSourceTest.cpp
@@ -28,12 +28,17 @@
 #define EXPECT_TOKEN_KIND(FormatTok, Kind) \
   do { \
 FormatToken *Tok = FormatTok;  \
-EXPECT_EQ((Tok)->Tok.getKind(), Kind) << *(Tok);   \
+EXPECT_EQ(Tok->Tok.getKind(), Kind) << *Tok;   \
+  } while (false);
+#define EXPECT_TOKEN_ID(FormatTok, Name)   \
+  do { \
+FormatToken *Tok = FormatTok;  \
+EXPECT_EQ(Tok->Tok.getKind(), tok::identifier) << *Tok;\
+EXPECT_EQ(Tok->TokenText, Name) << *Tok;   \
   } while (false);
 
 TEST_F(IndexedTokenSourceTest, EmptyInput) {
-  TokenList Tokens = lex("");
-  IndexedTokenSource Source(Tokens);
+  IndexedTokenSource Source(lex(""));
   EXPECT_FALSE(Source.isEOF());
   EXPECT_TOKEN_KIND(Source.getNextToken(), tok::eof);
   EXPECT_TRUE(Source.isEOF());
@@ -46,8 +51,7 @@
 }
 
 TEST_F(IndexedTokenSourceTest, NavigateTokenStream) {
-  TokenList Tokens = lex("int a;");
-  IndexedTokenSource Source(Tokens);
+  IndexedTokenSource Source(lex("int a;"));
   EXPECT_TOKEN_KIND(Source.peekNextToken(), tok::kw_int);
   EXPECT_TOKEN_KIND(Source.getNextToken(), tok::kw_int);
   EXPECT_EQ(Source.getPreviousToken(), nullptr);
@@ -60,11 +64,12 @@
   EXPECT_TOKEN_KIND(Source.peekNextToken(), tok::eof);
   EXPECT_TOKEN_KIND(Source.getNextToken(), tok::eof);
   EXPECT_TOKEN_KIND(Source.getPreviousToken(), tok::semi);
+  EXPECT_TOKEN_KIND(Source.getNextToken(), tok::eof);
+  EXPECT_TOKEN_KIND(Source.getPreviousToken(), tok::semi);
 }
 
 TEST_F(IndexedTokenSourceTest, ResetPosition) {
-  TokenList Tokens = lex("int a;");
-  IndexedTokenSource Source(Tokens);
+  IndexedTokenSource Source(lex("int a;"));
   Source.getNextToken();
   unsigned Position = Source.getPosition();
   Source.getNextToken();
@@ -73,6 +78,50 @@
   EXPECT_TOKEN_KIND(Source.setPosition(Position), tok::kw_int);
 }
 
+TEST_F(IndexedTokenSourceTest, InsertTokens) {
+  IndexedTokenSource Source(lex("A1 A2"));
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("B1 B2")), "B1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "B2");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A2");
+}
+
+TEST_F(IndexedTokenSourceTest, InsertTokensAtEOF) {
+  IndexedTokenSource Source(lex("A1"));
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_KIND(Source.getNextToken(), tok::eof);
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("B1 B2")), "B1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "B2");
+  EXPECT_TOKEN_KIND(Source.getNextToken(), tok::eof);
+}
+
+TEST_F(IndexedTokenSourceTest, InsertTokensRecursive) {
+  IndexedTokenSource Source(lex("A1"));
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  // A1
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("B1")), "B1");
+  // B1 A1
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("C1")), "C1");
+  // C1 B1 A1
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("D1")), "D1");
+  // D1 C1 B1 A1
+  EXPECT_TOKEN_ID(Source.getNextToken(), "C1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "B1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+}
+
+TEST_F(IndexedTokenSourceTest, InsertTokensRecursiveAtEndOfSequence) {
+  IndexedTokenSource Source(lex("A1"));
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("B1")), "B1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("C1")), "C1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("D1")), "D1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/UnwrappedLineParser.h
===
--- clang/lib/Format/UnwrappedLineParser.h
+++ clang/lib/Format/UnwrappedLineParser.h
@@ -280,9 +280,6 @@
   FormatTokenSource *Tokens;
   Unwrapp

[PATCH] D143496: [clangd] Add support for missing includes analysis.

2023-02-15 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

Thanks! Details mostly looks good, but i think we had different ideas about how 
the final diagnostics should look like. Let's try to clear that up a bit. My 
suggested proposal is:

- Having a main diagnostic for each symbol that doesn't have a satisfying 
include in the main file, attached to the first use of the symbol, with message 
` providing 'ns::Foo' is not directly included`, with severity warning
- Having notes attached to this main diagnostic, on rest of the references of 
the same symbol inside the main file, with message `Also used here`, with 
severity info
- Having a single fix attached to main diagnostic inserting the first provider.

I believe in the future the main diagnostic message should change to `No header 
providing 'ns::Foo' is directly included`, and we should have multiple fixes 
attached. But there's value in explicitly spelling the header name when there's 
only one fix to get rid of indirections.

This means:

  + we'll emit different diagnostics for each unsatisfied symbol even if 
they're satisfied by the same provider.
  + the user will be able to see usage sites for each symbol as a whole (as 
we're attaching them as notes), and if need be can make a decision around 
dropping the dependency or introducing a forward decl.
  + we won't "butcher" the diagnostic panel with 100 duplicated diagnostics all 
talking about the same thing.
  - in certain editors, like vscode, related information doesn't show up as 
extra decorations in code. so if the user ignores diagnostic panel and the 
first usage of a symbol is not visible. they'll likely miss the finding.

WDYT about this approach? any other alternatives you've in mind? I think it 
might make sense to get others opinion's here as well. Especially around the 
diagnostic message, as usually whatever is convenient to a single person isn't 
necessarily clear/obvious for every one :D




Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:516
+
+  std::vector Macros =
+  collectMacroReferences(AST);

VitaNuo wrote:
> kadircet wrote:
> > 
> Why would you use `auto` here? The return type is not obvious from the 
> function call.
> 
> The style guide says: "types that you and your reviewer experience as 
> unnecessary clutter will very often provide useful information to others. For 
> example, you can assume that the return type of `make_unique()` is 
> obvious, but the return type of `MyWidgetFactory()` probably isn't." 
> (http://go/cstyle#Type_deduction)
well, feel free to keep it. but at least, inside clangd codebase, we use auto 
frequently (maybe more than we should). especially in cases like this where a 
declaration would otherwise fit a single line and because the name of the 
initializer implies this will be a container of macro references and any extra 
details about the container is probably irrelevant.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:547
+convertIncludes(const SourceManager &SM,
+std::vector MainFileIncludes) {
+  include_cleaner::Includes Includes;

VitaNuo wrote:
> kadircet wrote:
> > you can just pass an `llvm::ArrayRef` to prevent a copy
> By preventing a copy, do you mean that the construction of 
> `llvm::ArrayRef` will only copy a pointer to the data rather than 
> the whole vector? AFAIU `const std::vector&` should be even better 
> then, no copies involved. CMIIW.
well from performance-wise they're pretty close, passing by const ref doesn't 
mean you don't do any copies, it'll still require address of the entity to be 
signalled somehow, which is a pointer copy. passing an arrayref implies copying 
a pointer to data and the size (so it's slightly worse in that regard). but it 
can represent any chunk of contiguous memory, the data source doesn't need to 
be a vector. moreover you can easily pass a slice of a vector rather than the 
whole vector etc.

the performance implications rarely matters in practice, and the abstraction it 
provides on the interfaces is usually a benefit, e.g. if we were to change 
underlying type from vector to llvm::SmallVector, the APIs would still work and 
you don't need to think about any concrete types. hence we tend to prefer 
having ArrayRef on API boundaries whenever possible.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:512
+include_cleaner::Includes
+convertIncludes(const SourceManager &SM,
+const std::vector &MainFileIncludes) {

since this is a local symbol, either mark it as `static` or move it to 
anonymous namespace above so that it won't be visible to other translation 
units.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:513
+convertIncludes(const SourceManager &SM,
+const std::vector &MainFileIncludes) {
+  include_cleaner::Includes Includes;

nit: you can use `llvm::ArrayRef` instead of a `const std::vector &

[clang] 1f818f6 - [clang-format] assert(false) -> llvm_unreachable

2023-02-15 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2023-02-15T14:10:09+01:00
New Revision: 1f818f63b829f3038a9fd605bf90348ba58cd981

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

LOG: [clang-format] assert(false) -> llvm_unreachable

Avoids warnings in -asserts builds.

FormatTokenSource.h:240:3: error: non-void function does not return a value 
[-Werror,-Wreturn-type]
  }
  ^

Added: 


Modified: 
clang/lib/Format/FormatTokenSource.h

Removed: 




diff  --git a/clang/lib/Format/FormatTokenSource.h 
b/clang/lib/Format/FormatTokenSource.h
index 8bf7e6932c89..0be46287f6b7 100644
--- a/clang/lib/Format/FormatTokenSource.h
+++ b/clang/lib/Format/FormatTokenSource.h
@@ -236,7 +236,7 @@ class ScopedMacroState : public FormatTokenSource {
   }
 
   FormatToken *insertTokens(ArrayRef Tokens) override {
-assert(false && "Cannot insert tokens while parsing a macro.");
+llvm_unreachable("Cannot insert tokens while parsing a macro.");
   }
 
 private:



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


[clang] 861764b - [NVPTX] Fix NVPTX output name in the driver with `-save-temps`

2023-02-15 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2023-02-15T07:39:59-06:00
New Revision: 861764b1c5f7fc31601655f01d84407d42013c30

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

LOG: [NVPTX] Fix NVPTX output name in the driver with `-save-temps`

Summary:
Currently, OpenMP and direct compilation uses an NVPTX toolchain to
directly invoke the CUDA tools from Clang to do the assembling and
linking of NVPTX codes. This breaks under `-save-temps` because of a
workaround. The `nvlink` linker does not accept `.o` files, so we need
to be selective when we output these. The previous logic keyed off of
presense in the temp files and wasn't a great solution. Change this to
just query the input args for `-c` to see if we stop at the assembler.

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Cuda.cpp
clang/test/Driver/cuda-cross-compiling.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index 6d710fd4275e0..95d932e1eb9b7 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -446,13 +446,8 @@ void NVPTX::Assembler::ConstructJob(Compilation &C, const 
JobAction &JA,
   std::string OutputFileName = TC.getInputFilename(Output);
 
   // If we are invoking `nvlink` internally we need to output a `.cubin` file.
-  // Checking if the output is a temporary is the cleanest way to determine
-  // this. Putting this logic in `getInputFilename` isn't an option because it
-  // relies on the compilation.
   // FIXME: This should hopefully be removed if NVIDIA updates their tooling.
-  if (Output.isFilename() &&
-  llvm::find(C.getTempFiles(), Output.getFilename()) !=
-  C.getTempFiles().end()) {
+  if (!C.getInputArgs().getLastArg(options::OPT_c)) {
 SmallString<256> Filename(Output.getFilename());
 llvm::sys::path::replace_extension(Filename, "cubin");
 OutputFileName = Filename.str();

diff  --git a/clang/test/Driver/cuda-cross-compiling.c 
b/clang/test/Driver/cuda-cross-compiling.c
index 992fda8deb33e..9750f09508010 100644
--- a/clang/test/Driver/cuda-cross-compiling.c
+++ b/clang/test/Driver/cuda-cross-compiling.c
@@ -43,6 +43,8 @@
 //
 // RUN: %clang -target nvptx64-nvidia-cuda -march=sm_61 -c -### %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=OBJECT %s
+// RUN: %clang -target nvptx64-nvidia-cuda -save-temps -march=sm_61 -c -### %s 
2>&1 \
+// RUN:   | FileCheck -check-prefix=OBJECT %s
 
 //  OBJECT: -cc1" "-triple" "nvptx64-nvidia-cuda" "-S" {{.*}} 
"-target-cpu" "sm_61" "-target-feature" "+ptx{{[0-9]+}}" {{.*}} "-o" 
"[[PTX:.+]].s"
 // OBJECT-NEXT: ptxas{{.*}}"-m64" "-O0" "--gpu-name" "sm_61" "--output-file" 
"[[OBJ:.+]].o" "[[PTX]].s" "-c"



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


[PATCH] D144074: [clangd] Hide inlay hints when using a macro as a calling argument that with a param comment

2023-02-15 Thread Younan Zhang via Phabricator via cfe-commits
zyounan created this revision.
Herald added subscribers: kadircet, arphaman.
Herald added a project: All.
zyounan added reviewers: kadircet, nridge.
zyounan added a comment.
zyounan retitled this revision from "[clangd] Hide extra inlay hints for macro 
as argument" to "[clangd] Hide inlay hints when using a macro as a calling 
argument that with a param comment".
zyounan published this revision for review.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Note that we still have some issues on inlay hints with macro expansion even 
after D133982 .

  void func(int a, int b)
  #define CALL(a, b) func(int(a), b)
  
  CALL(3, 4)  // CALL(3, b: 4)

This is because `spelledForExpanded` doesn't return counterpart spelling ( 
`int(3)` -> `3` ). (I guess it is due to patch D134618 
.)

  void func(int a, int b)
  void work(int a, int &b)
  #define CALL(a, b) { func(int(a), b); work(a, b); }
  
  int z = 42;
  CALL(3, z)  // CALL(a: 3, &b:b: 4)

This is because call expression handling logic (i.e. 
`InlayHintVisitor::processCall`) doesn't know the macro expansion context of 
expression, resulting producing two inlay hints at the same spelled position.




Comment at: clang-tools-extra/clangd/InlayHints.cpp:521
+auto Decomposed = SM.getDecomposedExpansionLoc(ExprStartLoc);
 if (Decomposed.first != MainFileID)
   return false;

stupid question: I was suspicious with this check that when would 
`Decomposed.first` not being the same as MainFileID? Should the "top-caller" of 
the macro always be in main file? I didn't find a case that differs, except 
when `getDecomposedLoc` provides wrong FileID.


We don't want to produce inlay hints for arguments for which
user has left param name comments. But we're not decomposing
location of the parameter correctly at the moment because the
location we've passed into `SM.getDecomposedLoc` is not always
FileID.

Fixes clangd/clangd#1495


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144074

Files:
  clang-tools-extra/clangd/InlayHints.cpp
  clang-tools-extra/clangd/unittests/InlayHintTests.cpp


Index: clang-tools-extra/clangd/unittests/InlayHintTests.cpp
===
--- clang-tools-extra/clangd/unittests/InlayHintTests.cpp
+++ clang-tools-extra/clangd/unittests/InlayHintTests.cpp
@@ -1050,9 +1050,15 @@
 void bar() {
   foo(/*param*/42);
   foo( /* param = */ 42);
+#define X 42
+#define Y X
+#define Z(...) Y
+  foo(/*param=*/Z(a));
+  foo($macro[[Z(a)]]);
   foo(/* the answer */$param[[42]]);
 }
   )cpp",
+   ExpectedHint{"param: ", "macro"},
ExpectedHint{"param: ", "param"});
 }
 
Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -517,7 +517,7 @@
   bool isPrecededByParamNameComment(const Expr *E, StringRef ParamName) {
 auto &SM = AST.getSourceManager();
 auto ExprStartLoc = SM.getTopMacroCallerLoc(E->getBeginLoc());
-auto Decomposed = SM.getDecomposedLoc(ExprStartLoc);
+auto Decomposed = SM.getDecomposedExpansionLoc(ExprStartLoc);
 if (Decomposed.first != MainFileID)
   return false;
 


Index: clang-tools-extra/clangd/unittests/InlayHintTests.cpp
===
--- clang-tools-extra/clangd/unittests/InlayHintTests.cpp
+++ clang-tools-extra/clangd/unittests/InlayHintTests.cpp
@@ -1050,9 +1050,15 @@
 void bar() {
   foo(/*param*/42);
   foo( /* param = */ 42);
+#define X 42
+#define Y X
+#define Z(...) Y
+  foo(/*param=*/Z(a));
+  foo($macro[[Z(a)]]);
   foo(/* the answer */$param[[42]]);
 }
   )cpp",
+   ExpectedHint{"param: ", "macro"},
ExpectedHint{"param: ", "param"});
 }
 
Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -517,7 +517,7 @@
   bool isPrecededByParamNameComment(const Expr *E, StringRef ParamName) {
 auto &SM = AST.getSourceManager();
 auto ExprStartLoc = SM.getTopMacroCallerLoc(E->getBeginLoc());
-auto Decomposed = SM.getDecomposedLoc(ExprStartLoc);
+auto Decomposed = SM.getDecomposedExpansionLoc(ExprStartLoc);
 if (Decomposed.first != MainFileID)
   return false;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D138777: [clang-tidy] Add check bugprone-multiple-new-in-one-expression.

2023-02-15 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 497654.
balazske added a comment.

make check available in all C++ versions, add compound operator related test 
and code


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138777

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone/multiple-new-in-one-expression.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/multiple-new-in-one-expression.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/multiple-new-in-one-expression.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/multiple-new-in-one-expression.cpp
@@ -0,0 +1,183 @@
+// RUN: %check_clang_tidy -std=c++11 -check-suffixes=ALL,CPP11 %s bugprone-multiple-new-in-one-expression %t
+// RUN: %check_clang_tidy -std=c++17 -check-suffixes=ALL,CPP17 %s bugprone-multiple-new-in-one-expression %t
+
+namespace std {
+typedef __typeof__(sizeof(0)) size_t;
+enum class align_val_t : std::size_t {};
+class exception {};
+class bad_alloc : public exception {};
+struct nothrow_t {};
+extern const nothrow_t nothrow;
+} // namespace std
+
+void *operator new(std::size_t, const std::nothrow_t &) noexcept;
+void *operator new(std::size_t, std::align_val_t, const std::nothrow_t &) noexcept;
+void *operator new(std::size_t, void *) noexcept;
+void *operator new(std::size_t, char);
+
+struct B;
+
+struct A { int VarI; int *PtrI; B *PtrB; };
+
+struct B { int VarI; };
+
+struct G {
+  G(A*, B*) {}
+  int operator+=(A *) { return 3; };
+};
+
+int f(int);
+int f(A*);
+int f(A*, B*);
+int f(int, B*);
+int f(G, G);
+int f(B*);
+void f1(void *, void *);
+A *g(A *);
+
+G operator+(const G&, const G&);
+
+void test_function_parameter(A *XA, B *XB) {
+  (void)f(new A, new B);
+  try {
+(void)f(new A, new B);
+  }
+  catch (A) {};
+  try {
+(void)f(new A, new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:13: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception; order of these allocations is undefined [
+(void)f(f(new A, new B));
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+int X = f(new A, new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+X = f(new A, new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:11: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+X = 1 + f(new A, new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+
+(void)f(g(new A), new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+
+(void)f(1 + f(new A), new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:19: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+(void)f(XA = new A, new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:18: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+(void)f(1 + f(new A), XB = new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:19: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+  }
+  catch (std::exception) {}
+}
+
+void test_operator(G *G1) {
+  (void)(f(new A) + f(new B));
+  try {
+(void)(f(new A) + f(new B));
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:14: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+(void)f(f(new A) + f(new B));
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+int X = f(new A) + f(new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+X = f(new A) + f(new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:11: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+X = 1 + f(new A) + 1 + f(new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+
+(void)(f

[PATCH] D144100: [clang] Fix a bug that allowed some overflowing octal escape sequences

2023-02-15 Thread Sergei Barannikov via Phabricator via cfe-commits
barannikov88 created this revision.
Herald added a project: All.
barannikov88 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/D144100

Files:
  clang/lib/Lex/LiteralSupport.cpp
  clang/test/Lexer/char-escapes-delimited.c


Index: clang/test/Lexer/char-escapes-delimited.c
===
--- clang/test/Lexer/char-escapes-delimited.c
+++ clang/test/Lexer/char-escapes-delimited.c
@@ -58,6 +58,8 @@
 #if __WCHAR_MAX__ > 0x
   unsigned d = L'\o{377}'; // ext-warning {{extension}} cxx2b-warning 
{{C++2b}}
   unsigned e = L'\o{400}'; // expected-error {{octal escape sequence 
out of range}}
+  unsigned f = L'\o{1000}'; // expected-error {{octal escape sequence 
out of range}}
+  unsigned g = L'\o{2000}'; // expected-error {{octal escape sequence 
out of range}}
 #else
   unsigned d = L'\o{17}'; // ext-warning {{extension}} cxx2b-warning 
{{C++2b}}
   unsigned e = L'\o{20}'; // expected-error {{octal escape sequence out of 
range}}
Index: clang/lib/Lex/LiteralSupport.cpp
===
--- clang/lib/Lex/LiteralSupport.cpp
+++ clang/lib/Lex/LiteralSupport.cpp
@@ -263,7 +263,8 @@
 ThisTokBuf++;
 continue;
   }
-  if (ResultChar & 0x02000)
+  // About to shift out a digit?
+  if (ResultChar & 0xE000)
 Overflow = true;
 
   ResultChar <<= 3;


Index: clang/test/Lexer/char-escapes-delimited.c
===
--- clang/test/Lexer/char-escapes-delimited.c
+++ clang/test/Lexer/char-escapes-delimited.c
@@ -58,6 +58,8 @@
 #if __WCHAR_MAX__ > 0x
   unsigned d = L'\o{377}'; // ext-warning {{extension}} cxx2b-warning {{C++2b}}
   unsigned e = L'\o{400}'; // expected-error {{octal escape sequence out of range}}
+  unsigned f = L'\o{1000}'; // expected-error {{octal escape sequence out of range}}
+  unsigned g = L'\o{2000}'; // expected-error {{octal escape sequence out of range}}
 #else
   unsigned d = L'\o{17}'; // ext-warning {{extension}} cxx2b-warning {{C++2b}}
   unsigned e = L'\o{20}'; // expected-error {{octal escape sequence out of range}}
Index: clang/lib/Lex/LiteralSupport.cpp
===
--- clang/lib/Lex/LiteralSupport.cpp
+++ clang/lib/Lex/LiteralSupport.cpp
@@ -263,7 +263,8 @@
 ThisTokBuf++;
 continue;
   }
-  if (ResultChar & 0x02000)
+  // About to shift out a digit?
+  if (ResultChar & 0xE000)
 Overflow = true;
 
   ResultChar <<= 3;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D143142: [clang][lex] Enable Lexer to grow its buffer

2023-02-15 Thread David Rector via Phabricator via cfe-commits
davrec added a comment.

Only had a chance to give it a once over, I will look through more closely 
later, def by this weekend.  Main thing is I think we shouldn't be exposing the 
buffer pointers after this change, i.e. no public function should return `const 
char *`, unless I'm missing something.  If that box is checked and performance 
cost is negligible I'd give this the thumbs up.




Comment at: clang/include/clang/Lex/Lexer.h:307
   /// Return the current location in the buffer.
-  const char *getBufferLocation() const { return BufferPtr; }
+  const char *getBufferLocation() const {
+assert(BufferOffset <= BufferSize && "Invalid buffer state");

I think I'd like this to return `unsigned`; i.e. I think after this patch we 
should not even be publicly exposing buffer locations as pointers, IIUC.  A 
brief search for uses of `getBufferLocation()` (there aren't many) suggests 
this would be probably be fine and indeed would get rid of some unnecessary 
pointer arithmetic.  And indeed if anything really needs that `const char *` 
that might be a red flag to investigate further.



Comment at: clang/include/clang/Lex/Lexer.h:609
 
-  bool CheckUnicodeWhitespace(Token &Result, uint32_t C, const char *CurPtr);
+  bool CheckUnicodeWhitespace(Token &Result, uint32_t C, unsigned CurOffset);
 

FWIW it sucks that `uint32_t` is already sprinkled throughout the interface 
alongside `unsigned`, wish just one was used consistently, but that does not 
need to be addressed in this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143142

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


[PATCH] D143430: [C2x] Implement the `unreachable` macro for WG14 N2826

2023-02-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Headers/stddef.h:108
+__STDC_VERSION__ >= 202000L
+#define unreachable() __builtin_unreachable()
+#endif /* defined(__need_STDDEF_H_misc) && >= C23 */

erichkeane wrote:
> Is this REALLY required to be a macro by standard?  Is it so they don't have 
> to steal the word/can do #undef?  This is going to result in a worse 
> diagnostic here any time we diagnose on this line.
Yes, it's required to be a macro by the C standard.  According to my personal 
notes:

This led us up to a preference poll, does WG14 prefer the syntax variant over 
the macro variant in N2826? 3/12/5 (no consensus). Does WG14 prefer to put the 
macro into  as in N2826 in C23? 11/2/7 (consensus). Does WG14 want to 
adopt the unreachable feature Change 5 & 6 with stddef.h in place of HEADER.h 
into C23? 13/2/6 (consensus).

I don't think the diagnostic behavior here will be any different than for 
`offsetof` (defined a few lines below), right?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143430

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


[PATCH] D143430: [C2x] Implement the `unreachable` macro for WG14 N2826

2023-02-15 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Headers/stddef.h:108
+__STDC_VERSION__ >= 202000L
+#define unreachable() __builtin_unreachable()
+#endif /* defined(__need_STDDEF_H_misc) && >= C23 */

aaron.ballman wrote:
> erichkeane wrote:
> > Is this REALLY required to be a macro by standard?  Is it so they don't 
> > have to steal the word/can do #undef?  This is going to result in a worse 
> > diagnostic here any time we diagnose on this line.
> Yes, it's required to be a macro by the C standard.  According to my personal 
> notes:
> 
> This led us up to a preference poll, does WG14 prefer the syntax variant over 
> the macro variant in N2826? 3/12/5 (no consensus). Does WG14 prefer to put 
> the macro into  as in N2826 in C23? 11/2/7 (consensus). Does WG14 
> want to adopt the unreachable feature Change 5 & 6 with stddef.h in place of 
> HEADER.h into C23? 13/2/6 (consensus).
> 
> I don't think the diagnostic behavior here will be any different than for 
> `offsetof` (defined a few lines below), right?
`offsetof` is what made me ask this question :D I guess we do the whole 
'macro-like' escape in other places, but everything here is already crap, so I 
guess this is no different.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143430

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


[PATCH] D143210: PowerPC] Include vector bool and pixel when emitting lax warning

2023-02-15 Thread Amy Kwan via Phabricator via cfe-commits
amyk added inline comments.



Comment at: clang/lib/Sema/SemaExpr.cpp:9845
 if (anyAltivecTypes(RHSType, LHSType) &&
-!areSameVectorElemTypes(RHSType, LHSType))
+!Context.areCompatibleVectorTypes(RHSType, LHSType))
   Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)

Might be a silly question, but what does it mean to be a "compatible" vector 
type?



Comment at: clang/test/CodeGen/SystemZ/zvector.c:1
-// RUN: %clang_cc1 -triple s390x-linux-gnu -target-cpu z13 -fzvector 
-emit-llvm -o - -W -Wall -Werror %s | opt -S -passes=mem2reg | FileCheck %s
+// RUN: %clang_cc1 -triple s390x-linux-gnu -target-cpu z13 -fzvector 
-emit-llvm -o - -W -Wall -Werror -Wno-error=deprecate-lax-vec-conv-all \
+// RUN: %s | opt -S -passes=mem2reg | FileCheck %s

Nit: I think this line is still over 80 characters.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143210

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


[PATCH] D142822: [clang] ASTImporter: Fix importing of va_list types and declarations

2023-02-15 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy added a comment.

In D142822#4102795 , @balazske wrote:

> I looked at some of the failing tests but can not decide how to fix the 
> problems. The problem seems to be with the extra `namespace std` that was not 
> there before. I do not know what the tests are exactly testing. A part of the 
> tests can be fixed by adding new expect lines but these must be platform 
> specific.

It seems that your change in `Sema.cpp` creates the `std` namespace (or makes 
it visible?) in some situations where it's not declared by the code and should 
not be visible. I suspect that this behavior of your commit is not compliant 
with the standard, and there is precedent that Clang code pays attention to 
avoiding this sort of thing. For example commit 87f54060 

  introduces the simple testcase

  int *use_new(int N) {
return new int [N];
  }
  
  int std = 17;

which ensures that the `std` namespace is not visible even if a reference to 
`operator new` (whose full type references `std:bad_alloc`) is present.

I think the commit needs to be updated to avoid "leaking" the `std` namespace 
into code that do not declare it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142822

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


[PATCH] D142604: [Clang] Fix __VA_OPT__ implementation so that it treats the concatenation of a non-placemaker token and placemaker token as a non-placemaker token

2023-02-15 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.

I suspect the libc++ failure is because the patch is not rebased onto `main`. I 
remember seeing those issues a while back. I think it's unlikely to be this 
patch.


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

https://reviews.llvm.org/D142604

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


[PATCH] D144037: [clang-tidy] allow tests to use -config-file instead of -config

2023-02-15 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tools-extra/test/clang-tidy/check_clang_tidy.py:111
 if not any(
-[arg.startswith('-config=') for arg in self.clang_tidy_extra_args]):
+[arg.startswith('-config=') or arg.startswith('-config-file=') for arg 
in self.clang_tidy_extra_args]):
   self.clang_tidy_extra_args.append('-config={}')

ClockMan wrote:
> clang-tidy works with -config and with --config.
> But in documentation there is --config.
> 
> This python script should be updated to accept both single and double dash 
> arguments for config.
Please follow 80 characters limit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144037

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


[PATCH] D142822: [clang] ASTImporter: Fix importing of va_list types and declarations

2023-02-15 Thread Whisperity via Phabricator via cfe-commits
whisperity added subscribers: rsmith, whisperity.
whisperity added a comment.

In D142822#4095896 , @DavidSpickett 
wrote:

>   
> /home/david.spickett/llvm-project/clang/test/CodeGenCXX/cxx20-module-std-subst-2b.cpp:14:18:
>  error: reference to 'std' is ambiguous
>   void f(str> &s) {
>^
>   
> /home/david.spickett/llvm-project/clang/test/CodeGenCXX/cxx20-module-std-subst-2b.cpp:7:11:
>  note: candidate found by name lookup is 'std'
>   namespace std {
> ^

This looks like an ouchie of the highest order. I've been looking into 
Modules... 5-ish years ago, when it was still under design. There are two major 
concerns here, one is that we've been having a feature called //"Modules"// 
which was very Clang-specific (but a good proof-of-concept spiritual 
predecessor of what became the Standard Modules), and there are the standard 
modules. Now the file name explicitly mentions `cxx20` so this is likely about 
Standard Modules stuff. But to be fair, I'd take this implementation with a 
pinch of salt. Due to the lack of build-system support for Modules (there are 
some murmurs these days on the CMake GitLab about very soon adding meaningful 
support for this...) we do not really seem to have large-scale real-world 
experience as to how the standard really could be made working, **especially** 
in such a weird case like touching `namespace std` which //might// not be 
standards-compliant in the first place. (But yeah, we are test code here in a 
compiler; we can cut ourselves some slack.)

The code itself in these test files is really weird; it seems the test is 
centred around the idea that there are:

  // TU "A"
  module; // Code in the *global module fragment*
  namespace std { /* ... */ class basic_string; }
  
  export module Whatever; // Code in the public module interface unit of module 
Whatever.
  export /* ... */ using str = std::basic_string<...>;

So we have a symbol called `str`, which is publicly visible (to TUs importing 
`Whatever`), and the `namespace std` preceding `Whatever` in `TU "A"` is 
**not** visible but **reachable**? (The standard's way of expressing 
reachability is a kind of a mess , so I'd 
**definitely** try finding the people who worked in developing the actual 
solution that makes Standard Modules //work// in Clang... call the help of 
someone who's really expert on the Standard...) Perhaps @rsmith could help us 
clarify this situation.

You can't name `std::basic_string<...>` in the client code (because it is not 
//visible//), but you can depend on the symbol (e.g., `decltype` it to an 
alias!) because it is //reachable//!

And then you have

  // TU "B"
  import Whatever;
  
  namespace std { /* ... */ struct char_traits {}; }
  
  // use Sb mangling, not Ss, as this is not global-module std::char_traits
  /* ... */
  void f(str<..., std::char_traits<...>>)

In which there is "another" (?) `namespace std`, which should(??) also be part 
of the global module :

> The //global module// is the collection of all //global-module-fragments// 
> and all translation units that are not module units. Declarations appearing 
> in such a context are said to be in the //purview// of the global module.

I believe that `TU "B"` is **not** a module unit... But the comment (which is 
somehow misformatted?) in it would like to say that this `std` is, in fact, 
//not// part of the global module.

So somehow, the changes in this patch are making //both// `std`s part of the 
same //purview// (whatever that means, really...), thus resulting in ambiguity.

- Does this only happen on non-X86? @vabridgers, you could try adding a 
`--target=` flag locally in the test file to the compiler invocation and 
re-running the tests to verify. (Might need an LLVM build that is capable of 
generating code of other architectures.)
- My other suggestion would be putting some `->dump()` calls in your change, 
running the code and observing how the ASTs are looking in the states when 
execution is within the functions you're trying to change.




Comment at: clang/test/AST/ast-dump-traits.cpp:55
 // CHECK-NEXT: | `-ExpressionTraitExpr {{.*}}  'bool' 
__is_lvalue_expr
-// CHECK-NEXT: `-FunctionDecl {{.*}}  line:30:6{{( 
imported)?}} test_unary_expr_or_type_trait 'void ()'
+// CHECK-NEXT:  -FunctionDecl {{.*}}  line:30:6{{( 
imported)?}} test_unary_expr_or_type_trait 'void ()'
 // CHECK-NEXT:   `-CompoundStmt {{.*}} 

How is this change legit? Is this `FunctionDecl` node just "floating"? If so, 
why is there a `-` preceding in the textual dump? Usually top-level nodes do 
not have such a prefix.



Comment at: clang/test/AST/fixed_point.c:405
 
-//CHECK-NEXT: `-VarDecl {{.*}} literallast '_Accum' cinit
+//CHECK-NEXT:  -VarDecl {{.*}} literallast '_Accum' cinit
 //CHECK-NEXT:   `-FixedPointLiteral {{.*}} '_Accum' 1.0
-

[PATCH] D144037: [clang-tidy] allow tests to use -config-file instead of -config

2023-02-15 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp requested changes to this revision.
carlosgalvezp added a comment.
This revision now requires changes to proceed.

LGTM except the comments left by other reviewers! Marking it as "Request 
Changes" for visibility.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144037

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


[PATCH] D144047: [CUDA][SPIRV] Match builtin types and __GCC_ATOMIC_XXX_LOCK_FREE macros on host/device

2023-02-15 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

Making the builtin types consistent is necessary to keep struct layout 
consistent across host and device, but why do we need to make  
__GCC_ATOMIC_XXX_LOCK_FREE macros the same between the host and device? Is 
there any concrete issue if they are not the same?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144047

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


[PATCH] D144041: [clang-tidy] add primitive types for hungarian identifier-naming (unsigned char and void)

2023-02-15 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp accepted this revision.
carlosgalvezp added a comment.
This revision is now accepted and ready to land.

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144041

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


[PATCH] D142822: [clang] ASTImporter: Fix importing of va_list types and declarations

2023-02-15 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

But there should be a way to make the namespace "invisible" like it is done 
with `std::bad_alloc`, the linked commit seems to contain the code to "hide" 
the first std definition and this may not work any more. Another question is 
why this architecture has a probably not standard requirement. This may be a 
question for the discourse forum to reach the developers that can make a 
working fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142822

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


[PATCH] D138037: [analyzer] Remove unjustified assertion from EQClass::simplify

2023-02-15 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

I am ok with committing this to unblock people hitting this assert, but at the 
same time I wonder if we want to open a ticket on GitHub that we might want to 
rethink how some of this works.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138037

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


[clang] 6b991ba - [clang][dataflow] Change `transfer` API to take a reference.

2023-02-15 Thread Yitzhak Mandelbaum via cfe-commits

Author: Yitzhak Mandelbaum
Date: 2023-02-15T15:37:21Z
New Revision: 6b991ba486b64f09e7d90ebc1fc2118ab48c8bff

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

LOG: [clang][dataflow] Change `transfer` API to take a reference.

The provided `CFGElement` is never null, so a reference is a more precise type.

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
clang/include/clang/Analysis/FlowSensitive/Models/ChromiumCheckModel.h

clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
clang/include/clang/Analysis/FlowSensitive/NoopAnalysis.h
clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
clang/lib/Analysis/FlowSensitive/Models/ChromiumCheckModel.cpp
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
clang/unittests/Analysis/FlowSensitive/ChromiumCheckModelTest.cpp
clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp
clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
clang/unittests/Analysis/FlowSensitive/TransferBranchTest.cpp
clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
index d7ca721246757..3be29cfed0a9c 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -41,7 +41,7 @@ namespace dataflow {
 ///  must provide the following public members:
 ///   * `LatticeT initialElement()` - returns a lattice element that models the
 /// initial state of a basic block;
-///   * `void transfer(const CFGElement *, LatticeT &, Environment &)` - 
applies
+///   * `void transfer(const CFGElement &, LatticeT &, Environment &)` - 
applies
 /// the analysis transfer function for a given CFG element and lattice
 /// element.
 ///
@@ -122,8 +122,7 @@ class DataflowAnalysis : public TypeErasedDataflowAnalysis {
   void transferTypeErased(const CFGElement &Element, TypeErasedLattice &E,
   Environment &Env) final {
 Lattice &L = llvm::any_cast(E.Value);
-// FIXME: change the contract of `transfer` to take a reference.
-static_cast(this)->transfer(&Element, L, Env);
+static_cast(this)->transfer(Element, L, Env);
   }
 
   void transferBranchTypeErased(bool Branch, const Stmt *Stmt,
@@ -239,7 +238,7 @@ runDataflowAnalysis(
 class DataflowModel : public Environment::ValueModel {
 public:
   /// Return value indicates whether the model processed the `Element`.
-  virtual bool transfer(const CFGElement *Element, Environment &Env) = 0;
+  virtual bool transfer(const CFGElement &Element, Environment &Env) = 0;
 };
 
 } // namespace dataflow

diff  --git 
a/clang/include/clang/Analysis/FlowSensitive/Models/ChromiumCheckModel.h 
b/clang/include/clang/Analysis/FlowSensitive/Models/ChromiumCheckModel.h
index e65f40b0b726e..b4315e41d79fa 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Models/ChromiumCheckModel.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Models/ChromiumCheckModel.h
@@ -13,7 +13,6 @@
 #define CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_CHROMIUMCHECKMODEL_H
 
 #include "clang/AST/DeclCXX.h"
-#include "clang/AST/Stmt.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "llvm/ADT/DenseSet.h"
@@ -26,7 +25,7 @@ namespace dataflow {
 class ChromiumCheckModel : public DataflowModel {
 public:
   ChromiumCheckModel() = default;
-  bool transfer(const CFGElement *Element, Environment &Env) override;
+  bool transfer(const CFGElement &Element, Environment &Env) override;
 
 private:
   /// Declarations for `::logging::CheckError::.*Check`, lazily initialized.

diff  --git 
a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
 
b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
index 2d52ee5fc846d..23dfdd49e94d9 100644
--- 
a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
+++ 
b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
@@ -52,7 +52,7 @@ class UncheckedOptionalAccessModel
 
   static NoopLattice initialElement() { return {}; }
 
-  void transfer(const CFGElement *Elt, NoopLattice &L, Environment &Env);
+  void transfer(const CFGElement &Elt, NoopLattice &L, Environment &Env);
 
   ComparisonResult compare(QualType Type, const Value &Val1,
 

[PATCH] D143920: [clang][dataflow] Change `transfer` API to take a reference.

2023-02-15 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6b991ba486b6: [clang][dataflow] Change `transfer` API to 
take a reference. (authored by ymandel).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143920

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Models/ChromiumCheckModel.h
  
clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
  clang/include/clang/Analysis/FlowSensitive/NoopAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
  clang/lib/Analysis/FlowSensitive/Models/ChromiumCheckModel.cpp
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
  clang/unittests/Analysis/FlowSensitive/ChromiumCheckModelTest.cpp
  clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
  clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp
  clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
  clang/unittests/Analysis/FlowSensitive/TransferBranchTest.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -112,7 +112,7 @@
 
   static NonConvergingLattice initialElement() { return {0}; }
 
-  void transfer(const CFGElement *, NonConvergingLattice &E, Environment &) {
+  void transfer(const CFGElement &, NonConvergingLattice &E, Environment &) {
 ++E.State;
   }
 };
@@ -194,8 +194,8 @@
 
   static FunctionCallLattice initialElement() { return {}; }
 
-  void transfer(const CFGElement *Elt, FunctionCallLattice &E, Environment &) {
-auto CS = Elt->getAs();
+  void transfer(const CFGElement &Elt, FunctionCallLattice &E, Environment &) {
+auto CS = Elt.getAs();
 if (!CS)
   return;
 const auto *S = CS->getStmt();
@@ -350,8 +350,8 @@
 
   static NoopLattice initialElement() { return {}; }
 
-  void transfer(const CFGElement *Elt, NoopLattice &, Environment &Env) {
-auto CS = Elt->getAs();
+  void transfer(const CFGElement &Elt, NoopLattice &, Environment &Env) {
+auto CS = Elt.getAs();
 if (!CS)
   return;
 const auto *S = CS->getStmt();
@@ -508,8 +508,8 @@
 
   static NoopLattice initialElement() { return {}; }
 
-  void transfer(const CFGElement *Elt, NoopLattice &, Environment &Env) {
-auto CS = Elt->getAs();
+  void transfer(const CFGElement &Elt, NoopLattice &, Environment &Env) {
+auto CS = Elt.getAs();
 if (!CS)
   return;
 const Stmt *S = CS->getStmt();
@@ -1202,8 +1202,8 @@
 
   static NoopLattice initialElement() { return {}; }
 
-  void transfer(const CFGElement *Elt, NoopLattice &, Environment &Env) {
-auto CS = Elt->getAs();
+  void transfer(const CFGElement &Elt, NoopLattice &, Environment &Env) {
+auto CS = Elt.getAs();
 if (!CS)
   return;
 const Stmt *S = CS->getStmt();
Index: clang/unittests/Analysis/FlowSensitive/TransferBranchTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferBranchTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferBranchTest.cpp
@@ -44,7 +44,7 @@
   explicit TestPropagationAnalysis(ASTContext &Context)
   : DataflowAnalysis(Context) {}
   static TestLattice initialElement() { return TestLattice::bottom(); }
-  void transfer(const CFGElement *, TestLattice &, Environment &) {}
+  void transfer(const CFGElement &, TestLattice &, Environment &) {}
   void transferBranch(bool Branch, const Stmt *S, TestLattice &L,
   Environment &Env) {
 L.Branch = Branch;
Index: clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
@@ -124,9 +124,9 @@
 return ConstantPropagationLattice::bottom();
   }
 
-  void transfer(const CFGElement *E, ConstantPropagationLattice &Element,
+  void transfer(const CFGElement &E, ConstantPropagationLattice &Element,
 Environment &Env) {
-auto CS = E->getAs();
+auto CS = E.getAs();
 if (!CS)
   return;
 auto S = CS->getStmt();
Index: clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp
@@ -33

[PATCH] D144047: [CUDA][SPIRV] Match builtin types and __GCC_ATOMIC_XXX_LOCK_FREE macros on host/device

2023-02-15 Thread Shangwu Yao via Phabricator via cfe-commits
shangwuyao added a comment.

In D144047#4129154 , @yaxunl wrote:

> Making the builtin types consistent is necessary to keep struct layout 
> consistent across host and device, but why do we need to make  
> __GCC_ATOMIC_XXX_LOCK_FREE macros the same between the host and device? Is 
> there any concrete issue if they are not the same?

The reason is the same as NVPTX, see 
https://github.com/llvm/llvm-project/blob/22882c39df71397cc6f9774d18e87d06e016c55f/clang/lib/Basic/Targets/NVPTX.cpp#L137-L141.
 Without it, we won't be able to use libraries that statically check the 
__atomic_always_lock_free. I could add the comments in the code if that makes 
things more clear.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144047

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


[PATCH] D143891: [Clang] Adjust triviality computation in QualType::isTrivialType to C++20 cases.

2023-02-15 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added a comment.

In D143891#4122660 , @aaron.ballman 
wrote:

> This is an ABI breaking change, isn't it? (The type trait now returns 
> something different than it did before, which could change instantiations or 
> object layout.)

In my opinion, this is an argument for not fixing in a fix release of a 
specific version of Clang--not an argument for additional option control in new 
versions.
Instantiations change all the time from changes to constant expression 
evaluation, overload resolution, partial ordering rules for templates, etc.
As for object layout, I believe the language and the ABI rules for triviality 
diverged quite some time ago.

I know that the evaluation for this specific case was that we don't need to 
apply ABI versioning control for this because it only affects code using 
Concepts, but I think we will eventually need to (re)discover when ABI 
versioning control is the appropriate tool.

I propose an action item: Someone needed to review past application of the ABI 
versioning options to see if we can extract and document workable criteria 
(perhaps in https://clang.llvm.org/docs/InternalsManual.html).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143891

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


[PATCH] D144047: [CUDA][SPIRV] Match builtin types and __GCC_ATOMIC_XXX_LOCK_FREE macros on host/device

2023-02-15 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D144047#4129182 , @shangwuyao 
wrote:

> In D144047#4129154 , @yaxunl wrote:
>
>> Making the builtin types consistent is necessary to keep struct layout 
>> consistent across host and device, but why do we need to make  
>> __GCC_ATOMIC_XXX_LOCK_FREE macros the same between the host and device? Is 
>> there any concrete issue if they are not the same?
>
> The reason is the same as NVPTX, see 
> https://github.com/llvm/llvm-project/blob/22882c39df71397cc6f9774d18e87d06e016c55f/clang/lib/Basic/Targets/NVPTX.cpp#L137-L141.
>  Without it, we won't be able to use libraries that statically check the 
> __atomic_always_lock_free. I could add the comments in the code if that makes 
> things more clear.

I see. Better add some comments about that.

This also means backend needs to handle atomic operations not supported by 
hardware.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144047

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


[PATCH] D143691: Fix clang-formats IncludeCategory to match the documentation

2023-02-15 Thread Fabian Keßler via Phabricator via cfe-commits
Febbe updated this revision to Diff 497687.
Febbe marked 3 inline comments as done.
Febbe added a comment.

- Removed some, not required changes.
- Reverted mapOptional -> mapRequired change, since it might break existing 
configs


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143691

Files:
  clang/lib/Format/Format.cpp
  clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
  clang/lib/Tooling/Inclusions/IncludeStyle.cpp
  clang/unittests/Format/SortIncludesTest.cpp

Index: clang/unittests/Format/SortIncludesTest.cpp
===
--- clang/unittests/Format/SortIncludesTest.cpp
+++ clang/unittests/Format/SortIncludesTest.cpp
@@ -535,11 +535,18 @@
  "#include \"b.h\"\n",
  "a.cc"));
 
-  // Only recognize the first #include with a matching basename as main include.
+  // Todo (remove-before-merge): I consider the assumption, that there is only
+  // one main include as wrong.
+  // E.g. a.cpp -> a.priv.h && a.h
+  // E.g. a_test.cpp -> a_test.h && a.h
+  // Maybe add a "//clang-format pragma: not_main" to remove false positives
+
+  // Recognize all possible main #include's with a matching basename as main
+  // include.
   EXPECT_EQ("#include \"a.h\"\n"
+"#include \"llvm/a.h\"\n"
 "#include \"b.h\"\n"
-"#include \"c.h\"\n"
-"#include \"llvm/a.h\"\n",
+"#include \"c.h\"\n",
 sort("#include \"b.h\"\n"
  "#include \"a.h\"\n"
  "#include \"c.h\"\n"
Index: clang/lib/Tooling/Inclusions/IncludeStyle.cpp
===
--- clang/lib/Tooling/Inclusions/IncludeStyle.cpp
+++ clang/lib/Tooling/Inclusions/IncludeStyle.cpp
@@ -7,17 +7,26 @@
 //===--===//
 
 #include "clang/Tooling/Inclusions/IncludeStyle.h"
+#include 
 
 using clang::tooling::IncludeStyle;
 
 namespace llvm {
 namespace yaml {
 
+// Todo (remove before merge): changes here are required,
+// because the explicit override for the default values of 0 are moved from
+// the algorithm to this place
+// Since we can't make those values required, we must set the previously
+// intended default values here, to prevent behaviour changes.
+
+constexpr int DefaultPriority = std::numeric_limits::max();
+
 void MappingTraits::mapping(
 IO &IO, IncludeStyle::IncludeCategory &Category) {
   IO.mapOptional("Regex", Category.Regex);
-  IO.mapOptional("Priority", Category.Priority);
-  IO.mapOptional("SortPriority", Category.SortPriority);
+  IO.mapOptional("Priority", Category.Priority, DefaultPriority);
+  IO.mapOptional("SortPriority", Category.SortPriority, Category.Priority);
   IO.mapOptional("CaseSensitive", Category.RegexIsCaseSensitive);
 }
 
Index: clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
===
--- clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
+++ clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
@@ -12,6 +12,7 @@
 #include "clang/Lex/Lexer.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Path.h"
+#include 
 #include 
 
 namespace clang {
@@ -206,33 +207,33 @@
   }
 }
 
+constexpr int DefaultMainIncludePriority = 0;
+constexpr int DefaultMainIncludeSortPriority = 0;
+
 int IncludeCategoryManager::getIncludePriority(StringRef IncludeName,
bool CheckMainHeader) const {
-  int Ret = INT_MAX;
+  if (CheckMainHeader && IsMainFile && isMainHeader(IncludeName))
+return DefaultMainIncludePriority;
+
   for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
-if (CategoryRegexs[i].match(IncludeName)) {
-  Ret = Style.IncludeCategories[i].Priority;
-  break;
-}
-  if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
-Ret = 0;
-  return Ret;
+if (CategoryRegexs[i].match(IncludeName))
+  return Style.IncludeCategories[i].Priority;
+
+  return std::numeric_limits::max();
 }
 
 int IncludeCategoryManager::getSortIncludePriority(StringRef IncludeName,
bool CheckMainHeader) const {
-  int Ret = INT_MAX;
+  if (CheckMainHeader && IsMainFile && isMainHeader(IncludeName))
+return DefaultMainIncludeSortPriority;
+
   for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
-if (CategoryRegexs[i].match(IncludeName)) {
-  Ret = Style.IncludeCategories[i].SortPriority;
-  if (Ret == 0)
-Ret = Style.IncludeCategories[i].Priority;
-  break;
-}
-  if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
-Ret = 0;
-  return Ret;
+if (CategoryRegexs[i].match(IncludeName))
+  return Style.IncludeCategories[i].SortPriority;
+
+  return std::numeric_limits::max();
 }
+
 bool IncludeCategoryMan

[PATCH] D143342: [clang-tidy] Support std::format and std::print in readability-redundant-string-cstr

2023-02-15 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

Just a few more points then it should be good to land




Comment at: 
clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp:181-190
+
+  // Detect redundant 'c_str()' calls in parameters passed to std::print and
+  // std::format.
+  Finder->addMatcher(
+  traverse(
+  TK_AsIs,
+  callExpr(

Can this be wrapped in a check to make sure it only runs in c++20

Likewise `::std::print` is only c++23, so maybe:
```lang=c++
getLangOpts().CPlusPlus2B ? hasAnyName("::std::print", "::std::format") : 
hasAnyName("::std::format")
```



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/readability/redundant-string-cstr.cpp:1
-// RUN: %check_clang_tidy %s readability-redundant-string-cstr %t
+// RUN: %check_clang_tidy -std=c++20 %s readability-redundant-string-cstr %t
 

We shouldn't be removing tests from older language standards
Can all the changes made to the file be moved into a new file 
`redundant-string-cstr-cpp20.cpp`
Would likely either need to create a second file for c++23 or make use of the 
check-suffix to run the tests for std::print


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

https://reviews.llvm.org/D143342

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


[PATCH] D143891: [Clang] Adjust triviality computation in QualType::isTrivialType to C++20 cases.

2023-02-15 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a subscriber: rsmith.
erichkeane added a comment.

In D143891#4129214 , 
@hubert.reinterpretcast wrote:

> In D143891#4122660 , @aaron.ballman 
> wrote:
>
>> This is an ABI breaking change, isn't it? (The type trait now returns 
>> something different than it did before, which could change instantiations or 
>> object layout.)
>
> In my opinion, this is an argument for not fixing in a fix release of a 
> specific version of Clang--not an argument for additional option control in 
> new versions.
> Instantiations change all the time from changes to constant expression 
> evaluation, overload resolution, partial ordering rules for templates, etc.
> As for object layout, I believe the language and the ABI rules for triviality 
> diverged quite some time ago.
>
> I know that the evaluation for this specific case was that we don't need to 
> apply ABI versioning control for this because it only affects code using 
> Concepts, but I think we will eventually need to (re)discover when ABI 
> versioning control is the appropriate tool.
>
> I propose an action item: Someone needed to review past application of the 
> ABI versioning options to see if we can extract and document workable 
> criteria (perhaps in https://clang.llvm.org/docs/InternalsManual.html).

Before doing that amount of work, I'd see if we could convince @rsmith to just 
share what his rule for this was, I think it was quite reasonable the few times 
he enforced it, and he can likely better state it at least.  Even if he were to 
share here, I'm sure one of us would be willing to clean up his statement and 
put it in the Internals Manual.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143891

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


[PATCH] D144036: [clang-tidy] Add bugprone-enum-to-bool-conversion check

2023-02-15 Thread Piotr Zegar via Phabricator via cfe-commits
ClockMan created this revision.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a reviewer: njames93.
Herald added a project: All.
ClockMan updated this revision to Diff 497408.
ClockMan added a comment.
Eugene.Zelenko added reviewers: aaron.ballman, carlosgalvezp.
ClockMan updated this revision to Diff 497692.
ClockMan published this revision for review.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Removed "Offers fixes" from list.rst


ClockMan added a comment.

Correct copyrights and commit author


ClockMan added a comment.

Ready for review




Comment at: clang-tools-extra/clang-tidy/bugprone/EnumToBoolConversionCheck.h:28
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+  void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
+

Should language be checked for C++?



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone/enum-to-bool-conversion.rst:6
+
+Detect implicit and explicit casts of `enum` type into `bool` where `enum` type
+doesn't have a zero-value enumerator. If `enum` is used only to hold values

Please synchronize first statement with statement in Release Notes. Please use 
double back-ticks for language constructs.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone/enum-to-bool-conversion.rst:49
+
+Default value: '^$'.
+Regexp used to ignore usages of enum declarations that match regexp.

Please use single back-ticks for option values. Default value is usually placed 
after option description.


Detect implicit and explicit conversions of enum to bool,
when enum doesn't have a enumerator with value equal to 0.
In theory such conversion should always return TRUE.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144036

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/EnumToBoolConversionCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/EnumToBoolConversionCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/bugprone/enum-to-bool-conversion.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion-cpp11.cpp
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion.cpp
@@ -0,0 +1,119 @@
+// RUN: %check_clang_tidy -std=c++98-or-later %s bugprone-enum-to-bool-conversion %t -- \
+// RUN:   -config="{CheckOptions: [{key: bugprone-enum-to-bool-conversion.EnumIgnoreRegexp, value: '^::without::issue::IgnoredEnum$'}]}"
+
+namespace with::issue
+{
+
+typedef enum EStatus
+{
+SUCCESS   = 1,
+FAILURE   = 2,
+INVALID_PARAM = 3,
+UNKNOWN   = 4
+} Status;
+
+bool testEnumConversion(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:12: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return value;
+}
+
+bool testTypedefConversion(Status value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:12: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return value;
+}
+
+bool testExplicitConversion(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:30: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return static_cast(value);
+}
+
+bool testInIfConversion(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:9: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+if (value)
+{
+return false;
+}
+
+return true;
+}
+
+bool testWithNegation(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:16: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return not value;
+}
+
+}
+
+namespace without::issue
+{
+
+enum StatusWithZero
+{
+UNK  = 0,
+OK   = 1,
+NOT_OK = 2
+};
+
+bool testEnumConversion(StatusWithZero value)
+{
+return value;
+}
+
+enum WithDefault
+{
+Value0,
+Value1
+};
+
+bool testEnumConversion(WithDefault value)
+{
+return value;
+}
+
+enum WithNegative : int
+{
+Nen2 = -2,
+Nen1,
+Nen0
+};
+
+bool testEnumConversion(WithNegative value)
+{
+return value;
+}
+
+enum EStatus
+{
+SUCCESS

[PATCH] D143342: [clang-tidy] Support std::format and std::print in readability-redundant-string-cstr

2023-02-15 Thread Mike Crowe via Phabricator via cfe-commits
mikecrowe added a comment.

Thanks for the review and further suggestions.

Mike.




Comment at: 
clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp:181-190
+
+  // Detect redundant 'c_str()' calls in parameters passed to std::print and
+  // std::format.
+  Finder->addMatcher(
+  traverse(
+  TK_AsIs,
+  callExpr(

njames93 wrote:
> Can this be wrapped in a check to make sure it only runs in c++20
> 
> Likewise `::std::print` is only c++23, so maybe:
> ```lang=c++
> getLangOpts().CPlusPlus2B ? hasAnyName("::std::print", "::std::format") : 
> hasAnyName("::std::format")
> ```
I can do that. I had (presumably incorrectly) assumed that since and use of 
`std::print` and `std::format` in any previous version would be UB then it was 
safe to apply the check regardless of the C++ version.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/readability/redundant-string-cstr.cpp:1
-// RUN: %check_clang_tidy %s readability-redundant-string-cstr %t
+// RUN: %check_clang_tidy -std=c++20 %s readability-redundant-string-cstr %t
 

njames93 wrote:
> We shouldn't be removing tests from older language standards
> Can all the changes made to the file be moved into a new file 
> `redundant-string-cstr-cpp20.cpp`
> Would likely either need to create a second file for c++23 or make use of the 
> check-suffix to run the tests for std::print
My brief reading up on check-suffix implies that it could be used to keep 
everything in `redundant-string-cstr.cpp`, but that file is getting rather 
large anyway. Having `redundant-string-cstr-cpp20.cpp` also containing C++23 
tests might be a bit confusing. Having `redundant-string-cstr-cpp23.cpp` too 
would mean moving the format_args stuff to a header (which might be beneficial 
regardless.)

Anyway, I shall have a play and see what I can make work.

Do I need to add tests to ensure that the checks don't trigger when running 
against earlier standard versions?


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

https://reviews.llvm.org/D143342

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


[PATCH] D144047: [CUDA][SPIRV] Match builtin types and __GCC_ATOMIC_XXX_LOCK_FREE macros on host/device

2023-02-15 Thread Shangwu Yao via Phabricator via cfe-commits
shangwuyao updated this revision to Diff 497700.
shangwuyao added a comment.

Amend with comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144047

Files:
  clang/lib/Basic/Targets/SPIR.h
  clang/test/CodeGenCUDASPIRV/cuda-types.cu

Index: clang/test/CodeGenCUDASPIRV/cuda-types.cu
===
--- /dev/null
+++ clang/test/CodeGenCUDASPIRV/cuda-types.cu
@@ -0,0 +1,56 @@
+// 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 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
+// feature, "cx8"). Therefore, __CLANG_ATOMIC_LLONG_LOCK_FREE is 2 on the host,
+// but the value should be 1 for the device.
+//
+// Unlike CUDA, the width of SPIR-V POINTER type could differ between host and
+// device, because SPIR-V explicitly sets POINTER type width. So it is the
+// user's responsibility to choose the offload with the right POINTER size,
+// otherwise the values for __CLANG_ATOMIC_POINTER_LOCK_FREE could be different.
+
+// RUN: mkdir -p %t
+
+// RUN: %clang --cuda-host-only -nocudainc -nocudalib --offload=spirv32 -target i386-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/i386-host-defines-filtered
+// RUN: %clang --cuda-device-only -nocudainc -nocudalib --offload=spirv32 -target i386-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_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 -nocudalib --offload=spirv32 -target i386-windows-msvc -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/i386-msvc-host-defines-filtered
+// RUN: %clang --cuda-device-only -nocudainc -nocudalib --offload=spirv32 -target i386-windows-msvc -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/i386-msvc-device-defines-filtered
+// RUN: diff %t/i386-msvc-host-defines-filtered %t/i386-msvc-device-defines-filtered
+
+// RUN: %clang --cuda-host-only -nocudainc -nocudalib --offload=spirv64 -target x86_64-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/x86_64-host-defines-filtered
+// RUN: %clang --cuda-device-only -nocudainc -nocudalib --offload=spirv64 -target x86_64-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %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 -nocudalib --offload=spirv64 -target powerpc64-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/powerpc64-host-defines-filtered
+// RUN: %clang --cuda-device-only -nocudainc -nocudalib --offload=spirv64 -target powerpc64-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/powerpc64-device-defines-filtered
+// RUN: diff %t/powerpc64-host-defines-filtered %t/powerpc64-device-defines-filtered
+
+// RUN: %clang --cuda-host-only -nocudainc -nocudalib --offload=spirv64 -target x86_64-windows-msvc -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/x86_64-msvc-host-defines-filtered
+// RUN: %clang --cuda-device-only -nocudainc -nocudalib --offload=spirv64 -target x86_64-windows-msvc -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/x86_64-msvc-device-defines-filtered
+// RUN: diff %t/x86_64-msvc-host-defines-filtered %t/x86_64-msvc-device-defines-filtered
+
Index: clang/lib/Basic/Targets/SPIR.h
===
--- clang/lib/Basic/Targets/SPIR.h
+++ clang/lib/Basic/Targets/SPIR.h
@@ -13,6 +13,7 @@
 #ifndef LLVM_CLANG_LIB_BASIC_TARGETS_SPIR_H
 #define LLVM_CLANG_LIB_BASIC_TARGETS_SPIR_H
 
+#include "Targets.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
 #include "llvm/Support/Compiler.h"
@@ -79,8 +80,10 @@
 
 // Base 

[PATCH] D143891: [Clang] Adjust triviality computation in QualType::isTrivialType to C++20 cases.

2023-02-15 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson added a comment.

It's an interesting discussion, I just want to remind that this change is for 
triviality rules from P0848 (conditionally trivial member functions) which is 
only going to ship in Clang 16 anyway.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143891

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


[PATCH] D143691: Fix clang-formats IncludeCategory to match the documentation

2023-02-15 Thread Fabian Keßler via Phabricator via cfe-commits
Febbe updated this revision to Diff 497701.
Febbe added a comment.

Added requested tests:

- since we now support priorities, equal to 0 (the main include priority) 
sorting should work now for those.
- multiple files can be main-includes now, the tests expects that now.
- negative priorities do not override the main include priority anymore, which 
is also tested


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143691

Files:
  clang/lib/Format/Format.cpp
  clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
  clang/lib/Tooling/Inclusions/IncludeStyle.cpp
  clang/unittests/Format/SortIncludesTest.cpp

Index: clang/unittests/Format/SortIncludesTest.cpp
===
--- clang/unittests/Format/SortIncludesTest.cpp
+++ clang/unittests/Format/SortIncludesTest.cpp
@@ -8,6 +8,7 @@
 
 #include "FormatTestUtils.h"
 #include "clang/Format/Format.h"
+#include "clang/Tooling/Inclusions/IncludeStyle.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Debug.h"
 #include "gtest/gtest.h"
@@ -535,16 +536,48 @@
  "#include \"b.h\"\n",
  "a.cc"));
 
-  // Only recognize the first #include with a matching basename as main include.
+  // Todo (remove-before-merge): I consider the assumption, that there is only
+  // one main include as wrong.
+  // E.g. a.cpp -> a.priv.h && a.h
+  // E.g. a_test.cpp -> a_test.h && a.h
+  // Maybe add a "//clang-format pragma: not_main" to remove false positives
+
+  // Recognize all possible main #include's with a matching basename as main
+  // include.
+  EXPECT_EQ("#include \"a.h\"\n"
+"#include \"llvm/a.h\"\n"
+"#include \"b.h\"\n"
+"#include \"c.h\"\n",
+sort("#include \"b.h\"\n"
+ "#include \"a.h\"\n"
+ "#include \"c.h\"\n"
+ "#include \"llvm/a.h\"\n",
+ "a.cc"));
+
+  // Keep manually splitted groups in place
   EXPECT_EQ("#include \"a.h\"\n"
 "#include \"b.h\"\n"
 "#include \"c.h\"\n"
+"// no main:\n"
 "#include \"llvm/a.h\"\n",
 sort("#include \"b.h\"\n"
  "#include \"a.h\"\n"
  "#include \"c.h\"\n"
+ "// no main:\n"
  "#include \"llvm/a.h\"\n",
  "a.cc"));
+
+  // Keep both main files together (with priority 0)
+  Style.IncludeIsMainRegex = "([-_](test|unittest))?$";
+  EXPECT_EQ("#include \"a.h\"\n"
+"#include \"a_test.h\"\n"
+"#include \"b.h\"\n"
+"#include \"c.h\"\n",
+sort("#include \"b.h\"\n"
+ "#include \"a.h\"\n"
+ "#include \"c.h\"\n"
+ "#include \"a_test.h\"\n",
+ "a_test.cc"));
 }
 
 TEST_F(SortIncludesTest, LeavesMainHeaderFirstInAdditionalExtensions) {
@@ -762,6 +795,64 @@
  "#include \"c_main.h\"\n"
  "#include \"a_other.h\"\n",
  "c_main.cc", 0));
+  // All negative
+  Style.IncludeCategories = {{".*important_os_header.*", -3, 0, false},
+ {".*", -2, 0, false}};
+
+  EXPECT_EQ("#include \"important_os_header.h\"\n"
+"#include \"a_other.h\"\n"
+"#include \"c_main.h\"\n",
+sort("#include \"c_main.h\"\n"
+ "#include \"a_other.h\"\n"
+ "#include \"important_os_header.h\"\n",
+ "c_main.cc"));
+}
+
+TEST_F(SortIncludesTest, ZeroPriorities) {
+  Style.IncludeCategories = {{".*important_os_header.*", 0, -1, false},
+ {".*", 1, 0, false}};
+  EXPECT_EQ("#include \"important_os_header.h\"\n"
+"#include \"c_main.h\"\n"
+"#include \"a_other.h\"\n",
+sort("#include \"c_main.h\"\n"
+ "#include \"a_other.h\"\n"
+ "#include \"important_os_header.h\"\n",
+ "c_main.cc"));
+
+  // check stable when re-run
+  EXPECT_EQ("#include \"important_os_header.h\"\n"
+"#include \"c_main.h\"\n"
+"#include \"a_other.h\"\n",
+sort("#include \"important_os_header.h\"\n"
+ "#include \"c_main.h\"\n"
+ "#include \"a_other.h\"\n",
+ "c_main.cc", 0));
+
+  // All zero, sorted after name
+  Style.IncludeCategories = {{".*important_os_header.*", 0, 0, false},
+ {".*", 0, 0, false}};
+
+  EXPECT_EQ("#include \"a_other.h\"\n"
+"#include \"c_main.h\"\n"
+"#include \"important_os_header.h\"\n",
+sort("#include \"important_os_header.h\"\n"
+ "#include \"c_main.h\"\n"
+ "#include \"a_other.h\"\n",
+ "c_main.cc"));
+
+  // Grouped:
+  Style.IncludeBlocks = tooling::IncludeStyle::IBS_Regroup;
+  Style.IncludeCategories = {{".*i

[PATCH] D144047: [CUDA][SPIRV] Match builtin types and __GCC_ATOMIC_XXX_LOCK_FREE macros on host/device

2023-02-15 Thread Shangwu Yao via Phabricator via cfe-commits
shangwuyao added a comment.

In D144047#4129247 , @yaxunl wrote:

> In D144047#4129182 , @shangwuyao 
> wrote:
>
>> In D144047#4129154 , @yaxunl wrote:
>>
>>> Making the builtin types consistent is necessary to keep struct layout 
>>> consistent across host and device, but why do we need to make  
>>> __GCC_ATOMIC_XXX_LOCK_FREE macros the same between the host and device? Is 
>>> there any concrete issue if they are not the same?
>>
>> The reason is the same as NVPTX, see 
>> https://github.com/llvm/llvm-project/blob/22882c39df71397cc6f9774d18e87d06e016c55f/clang/lib/Basic/Targets/NVPTX.cpp#L137-L141.
>>  Without it, we won't be able to use libraries that statically check the 
>> __atomic_always_lock_free. I could add the comments in the code if that 
>> makes things more clear.
>
> I see. Better add some comments about that.
>
> This also means backend needs to handle atomic operations not supported by 
> hardware.

Yeah. It is probably the application developer's responsibility to not request 
atomics that are not supported by the hardware?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144047

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


[PATCH] D144011: [clang]Fix warning for signed conversion

2023-02-15 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D144011#4126853 , @MaskRay wrote:

> I think it makes sense for `-Wsign-conversion` to not warn for this LP64 
> case, like we don't emit a warning for `-m32`. I do not know whether we need 
> another diagnostic like `-Wshorten-64-to-32` for this case, but am inclined 
> to no.
>
> I wonder whether the newly added condition can be merged with the following 
> condition:
>
>   if ((!isa(Target) || !isa(Source)) &&
>   ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
>(!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
> LikelySourceRange.Width == TargetRange.Width))) {
> if (S.SourceMgr.isInSystemMacro(CC))

Yes. Will do.


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

https://reviews.llvm.org/D144011

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


[PATCH] D144011: [clang]Fix warning for signed conversion

2023-02-15 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 497703.
yaxunl added a comment.

revised by Fanrui's comments


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

https://reviews.llvm.org/D144011

Files:
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/sign-conversion.c


Index: clang/test/Sema/sign-conversion.c
===
--- clang/test/Sema/sign-conversion.c
+++ clang/test/Sema/sign-conversion.c
@@ -5,4 +5,8 @@
 void test(int x) {
   unsigned t0 = x; // expected-warning {{implicit conversion changes 
signedness}}
   unsigned t1 = (t0 == 5 ? x : 0); // expected-warning {{operand of ? changes 
signedness}}
+
+  // Clang has special treatment for left shift of literal '1'.
+  // Make sure there is no diagnostics.
+  long t2 = 1LL << x;
 }
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -14293,6 +14293,12 @@
 if (S.SourceMgr.isInSystemMacro(CC))
   return;
 
+if (SourceBT && SourceBT->isInteger() && TargetBT &&
+TargetBT->isInteger() &&
+Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
+  return;
+}
+
 unsigned DiagID = diag::warn_impcast_integer_sign;
 
 // Traditionally, gcc has warned about this under -Wsign-compare.


Index: clang/test/Sema/sign-conversion.c
===
--- clang/test/Sema/sign-conversion.c
+++ clang/test/Sema/sign-conversion.c
@@ -5,4 +5,8 @@
 void test(int x) {
   unsigned t0 = x; // expected-warning {{implicit conversion changes signedness}}
   unsigned t1 = (t0 == 5 ? x : 0); // expected-warning {{operand of ? changes signedness}}
+
+  // Clang has special treatment for left shift of literal '1'.
+  // Make sure there is no diagnostics.
+  long t2 = 1LL << x;
 }
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -14293,6 +14293,12 @@
 if (S.SourceMgr.isInSystemMacro(CC))
   return;
 
+if (SourceBT && SourceBT->isInteger() && TargetBT &&
+TargetBT->isInteger() &&
+Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
+  return;
+}
+
 unsigned DiagID = diag::warn_impcast_integer_sign;
 
 // Traditionally, gcc has warned about this under -Wsign-compare.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D143691: Fix clang-formats IncludeCategory to match the documentation

2023-02-15 Thread Fabian Keßler via Phabricator via cfe-commits
Febbe marked 2 inline comments as done.
Febbe added inline comments.



Comment at: clang/lib/Format/Format.cpp:1379
   LLVMStyle.IncludeStyle.IncludeCategories = {
-  {"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0, false},
-  {"^(<|\"(gtest|gmock|isl|json)/)", 3, 0, false},
-  {".*", 1, 0, false}};
+  {"^\"(llvm|llvm-c|clang|clang-c)/", 2, 2, false},
+  {"^(<|\"(gtest|gmock|isl|json)/)", 3, 3, false},

HazardyKnusperkeks wrote:
> Febbe wrote:
> > HazardyKnusperkeks wrote:
> > > I don't follow why this is necessary. And I don't feel comfortable with 
> > > it.
> > This **was** required, but is not required necessarily, my last update of 
> > the patch made this change most likely obsolete.
> > 
> > But the actual reason is, that `SortPriority` is described in the 
> > documentation as "optional value which is defaulted to `Priority`, if 
> > absent", but it is neither a (std::)optional value nor it was defaulted to 
> > Priority if absent.
> > It was indirectly updated from **0** to `Priority` in the algorithm.
> > 
> > Since I moved the buggy, re-initialization of `SortPriority` to the first 
> > initialization:
> > clang/lib/Tooling/Inclusions/IncludeStyle.cpp:L20 this change must also be 
> > covered by the tests: All zero initializations must now be default to 
> > `Priority` to not change the test behavior, which is what you want.
> > 
> > Either by creating a Constructor without `SortPriority`, which defaults to 
> > Priority,
> > creating a factory function, or by doing this for all tests manually.
> > 
> > 
> > Imagine the tests would also test the interpretation of the JSON input. 
> > Then the tests would not require an adjustment to be semantically equal.
> > 
> > But since I added Priority to the sorting after **this** change, this is 
> > kind of irrelevant.
> My main question is, does this change behavior? In either case, please add 
> some tests to show the difference, or the lack thereof.
I removed all changes to the tests, which do not change the behavior.

One test required a change. It assumed, that only one file can be a main 
include, which is, in my opinion, not correct. I've made the change, that all 
files, which are matched as main include are ordered with priority 0 (this 
especially means includes introduced by `IncludeIsMainRegex` and 
`IncludeIsMainSourceRegex`). The previous implementation ignored those, if 
another main file was found earlier. It could also result in unpredictable 
resorting.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143691

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


[clang] 97ba3c2 - [Clang][AMDGPU] Set LTO CG opt level based on Clang option

2023-02-15 Thread Scott Linder via cfe-commits

Author: Scott Linder
Date: 2023-02-15T17:34:35Z
New Revision: 97ba3c2bec48ca55cc842c6499b19b0b8a271951

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

LOG: [Clang][AMDGPU] Set LTO CG opt level based on Clang option

For AMDGCN default to mapping --lto-O# to --lto-CGO# in a 1:1 manner
(i.e. clang -O implies --lto-O and --lto-CGO).

Ensure there is a means to override this via -Xoffload-linker and begin
to claim these arguments to avoid incorrect warnings that they are not
used.

Reviewed By: yaxunl, MaskRay

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/lib/Driver/ToolChains/HIPAMD.cpp
clang/test/Driver/hip-toolchain-opt.hip

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index e6360fd8edc13..c179c4152cee4 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -567,6 +567,7 @@ void tools::addLTOOptions(const ToolChain &ToolChain, const 
ArgList &Args,
   ArgStringList &CmdArgs, const InputInfo &Output,
   const InputInfo &Input, bool IsThinLTO) {
   const bool IsOSAIX = ToolChain.getTriple().isOSAIX();
+  const bool IsAMDGCN = ToolChain.getTriple().isAMDGCN();
   const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
   const Driver &D = ToolChain.getDriver();
   if (llvm::sys::path::filename(Linker) != "ld.lld" &&
@@ -631,9 +632,12 @@ void tools::addLTOOptions(const ToolChain &ToolChain, 
const ArgList &Args,
 OOpt = "2";
 } else if (A->getOption().matches(options::OPT_O0))
   OOpt = "0";
-if (!OOpt.empty())
+if (!OOpt.empty()) {
   CmdArgs.push_back(
   Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "O" + OOpt));
+  if (IsAMDGCN)
+CmdArgs.push_back(Args.MakeArgString(Twine("--lto-CGO") + OOpt));
+}
   }
 
   if (Args.hasArg(options::OPT_gsplit_dwarf))

diff  --git a/clang/lib/Driver/ToolChains/HIPAMD.cpp 
b/clang/lib/Driver/ToolChains/HIPAMD.cpp
index ff797e5959a49..3131c8ed24639 100644
--- a/clang/lib/Driver/ToolChains/HIPAMD.cpp
+++ b/clang/lib/Driver/ToolChains/HIPAMD.cpp
@@ -152,8 +152,10 @@ void AMDGCN::Linker::constructLldCommand(Compilation &C, 
const JobAction &JA,
 
   addLinkerCompressDebugSectionsOption(TC, Args, LldArgs);
 
-  for (auto *Arg : Args.filtered(options::OPT_Xoffload_linker))
+  for (auto *Arg : Args.filtered(options::OPT_Xoffload_linker)) {
 LldArgs.push_back(Arg->getValue(1));
+Arg->claim();
+  }
 
   LldArgs.append({"-o", Output.getFilename()});
   for (auto Input : Inputs)

diff  --git a/clang/test/Driver/hip-toolchain-opt.hip 
b/clang/test/Driver/hip-toolchain-opt.hip
index a82323d3da966..501f9654a2580 100644
--- a/clang/test/Driver/hip-toolchain-opt.hip
+++ b/clang/test/Driver/hip-toolchain-opt.hip
@@ -57,6 +57,14 @@
 // RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
 // RUN: 2>&1 | FileCheck --check-prefixes=ALL,Og %s
 
+// RUN: %clang -### -O0 \
+// RUN:   -Xoffload-linker --lto-CGO2 \
+// RUN:   --target=x86_64-unknown-linux-gnu \
+// RUN:   --cuda-gpu-arch=gfx900 \
+// RUN:   -c -nogpulib \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck --check-prefixes=ALL,O0-CGO2 %s
+
 // ALL: "-cc1" "-triple" "amdgcn-amd-amdhsa"
 // DEFAULT-NOT: "-O{{.}}"
 // O0-SAME: "-O0"
@@ -66,6 +74,8 @@
 // Os-SAME: "-Os"
 // Oz-SAME: "-Oz"
 // Og-SAME: "-Og"
+// O0-CGO2-SAME: "-O0"
+// O0-CGO2-NOT: "--lto-CGO2"
 
 // ALL-NOT: "{{.*}}opt"
 
@@ -74,12 +84,22 @@
 // ALL: "{{.*}}lld{{.*}}" {{.*}} "-plugin-opt=mcpu=gfx900"
 // DEFAULT-NOT: "-plugin-opt=O{{.*}}"
 // O0-SAME: "-plugin-opt=O0"
+// O0-SAME: "--lto-CGO0"
 // O1-SAME: "-plugin-opt=O1"
+// O1-SAME: "--lto-CGO1"
 // O2-SAME: "-plugin-opt=O2"
+// O2-SAME: "--lto-CGO2"
 // O3-SAME: "-plugin-opt=O3"
+// O3-SAME: "--lto-CGO3"
 // Os-SAME: "-plugin-opt=O2"
+// Os-SAME: "--lto-CGO2"
 // Oz-SAME: "-plugin-opt=O2"
+// Oz-SAME: "--lto-CGO2"
 // Og-SAME: "-plugin-opt=O1"
+// Og-SAME: "--lto-CGO1"
+// O0-CGO2-SAME: "-plugin-opt=O0"
+// O0-CGO2-SAME: "--lto-CGO0"
+// O0-CGO2-SAME: "--lto-CGO2"
 
 // ALL: "-cc1" "-triple" "x86_64-unknown-linux-gnu"
 // DEFAULT-NOT: "-O{{.}}"
@@ -90,3 +110,5 @@
 // Os-SAME: "-Os"
 // Oz-SAME: "-Oz"
 // Og-SAME: "-Og"
+// O0-CGO2-SAME: "-O0"
+// O0-CGO2-NOT: "--lto-CGO2"



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


[PATCH] D142499: [Clang][AMDGPU] Set LTO CG opt level based on Clang option

2023-02-15 Thread Scott Linder via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG97ba3c2bec48: [Clang][AMDGPU] Set LTO CG opt level based on 
Clang option (authored by scott.linder).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142499

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/HIPAMD.cpp
  clang/test/Driver/hip-toolchain-opt.hip


Index: clang/test/Driver/hip-toolchain-opt.hip
===
--- clang/test/Driver/hip-toolchain-opt.hip
+++ clang/test/Driver/hip-toolchain-opt.hip
@@ -57,6 +57,14 @@
 // RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
 // RUN: 2>&1 | FileCheck --check-prefixes=ALL,Og %s
 
+// RUN: %clang -### -O0 \
+// RUN:   -Xoffload-linker --lto-CGO2 \
+// RUN:   --target=x86_64-unknown-linux-gnu \
+// RUN:   --cuda-gpu-arch=gfx900 \
+// RUN:   -c -nogpulib \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck --check-prefixes=ALL,O0-CGO2 %s
+
 // ALL: "-cc1" "-triple" "amdgcn-amd-amdhsa"
 // DEFAULT-NOT: "-O{{.}}"
 // O0-SAME: "-O0"
@@ -66,6 +74,8 @@
 // Os-SAME: "-Os"
 // Oz-SAME: "-Oz"
 // Og-SAME: "-Og"
+// O0-CGO2-SAME: "-O0"
+// O0-CGO2-NOT: "--lto-CGO2"
 
 // ALL-NOT: "{{.*}}opt"
 
@@ -74,12 +84,22 @@
 // ALL: "{{.*}}lld{{.*}}" {{.*}} "-plugin-opt=mcpu=gfx900"
 // DEFAULT-NOT: "-plugin-opt=O{{.*}}"
 // O0-SAME: "-plugin-opt=O0"
+// O0-SAME: "--lto-CGO0"
 // O1-SAME: "-plugin-opt=O1"
+// O1-SAME: "--lto-CGO1"
 // O2-SAME: "-plugin-opt=O2"
+// O2-SAME: "--lto-CGO2"
 // O3-SAME: "-plugin-opt=O3"
+// O3-SAME: "--lto-CGO3"
 // Os-SAME: "-plugin-opt=O2"
+// Os-SAME: "--lto-CGO2"
 // Oz-SAME: "-plugin-opt=O2"
+// Oz-SAME: "--lto-CGO2"
 // Og-SAME: "-plugin-opt=O1"
+// Og-SAME: "--lto-CGO1"
+// O0-CGO2-SAME: "-plugin-opt=O0"
+// O0-CGO2-SAME: "--lto-CGO0"
+// O0-CGO2-SAME: "--lto-CGO2"
 
 // ALL: "-cc1" "-triple" "x86_64-unknown-linux-gnu"
 // DEFAULT-NOT: "-O{{.}}"
@@ -90,3 +110,5 @@
 // Os-SAME: "-Os"
 // Oz-SAME: "-Oz"
 // Og-SAME: "-Og"
+// O0-CGO2-SAME: "-O0"
+// O0-CGO2-NOT: "--lto-CGO2"
Index: clang/lib/Driver/ToolChains/HIPAMD.cpp
===
--- clang/lib/Driver/ToolChains/HIPAMD.cpp
+++ clang/lib/Driver/ToolChains/HIPAMD.cpp
@@ -152,8 +152,10 @@
 
   addLinkerCompressDebugSectionsOption(TC, Args, LldArgs);
 
-  for (auto *Arg : Args.filtered(options::OPT_Xoffload_linker))
+  for (auto *Arg : Args.filtered(options::OPT_Xoffload_linker)) {
 LldArgs.push_back(Arg->getValue(1));
+Arg->claim();
+  }
 
   LldArgs.append({"-o", Output.getFilename()});
   for (auto Input : Inputs)
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -567,6 +567,7 @@
   ArgStringList &CmdArgs, const InputInfo &Output,
   const InputInfo &Input, bool IsThinLTO) {
   const bool IsOSAIX = ToolChain.getTriple().isOSAIX();
+  const bool IsAMDGCN = ToolChain.getTriple().isAMDGCN();
   const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
   const Driver &D = ToolChain.getDriver();
   if (llvm::sys::path::filename(Linker) != "ld.lld" &&
@@ -631,9 +632,12 @@
 OOpt = "2";
 } else if (A->getOption().matches(options::OPT_O0))
   OOpt = "0";
-if (!OOpt.empty())
+if (!OOpt.empty()) {
   CmdArgs.push_back(
   Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "O" + OOpt));
+  if (IsAMDGCN)
+CmdArgs.push_back(Args.MakeArgString(Twine("--lto-CGO") + OOpt));
+}
   }
 
   if (Args.hasArg(options::OPT_gsplit_dwarf))


Index: clang/test/Driver/hip-toolchain-opt.hip
===
--- clang/test/Driver/hip-toolchain-opt.hip
+++ clang/test/Driver/hip-toolchain-opt.hip
@@ -57,6 +57,14 @@
 // RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
 // RUN: 2>&1 | FileCheck --check-prefixes=ALL,Og %s
 
+// RUN: %clang -### -O0 \
+// RUN:   -Xoffload-linker --lto-CGO2 \
+// RUN:   --target=x86_64-unknown-linux-gnu \
+// RUN:   --cuda-gpu-arch=gfx900 \
+// RUN:   -c -nogpulib \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck --check-prefixes=ALL,O0-CGO2 %s
+
 // ALL: "-cc1" "-triple" "amdgcn-amd-amdhsa"
 // DEFAULT-NOT: "-O{{.}}"
 // O0-SAME: "-O0"
@@ -66,6 +74,8 @@
 // Os-SAME: "-Os"
 // Oz-SAME: "-Oz"
 // Og-SAME: "-Og"
+// O0-CGO2-SAME: "-O0"
+// O0-CGO2-NOT: "--lto-CGO2"
 
 // ALL-NOT: "{{.*}}opt"
 
@@ -74,12 +84,22 @@
 // ALL: "{{.*}}lld{{.*}}" {{.*}} "-plugin-opt=mcpu=gfx900"
 // DEFAULT-NOT: "-plugin-opt=O{{.*}}"
 // O0-SAME: "-plugin-opt=O0"
+// O0-SAME: "--lto-CGO0"
 // O1-SAME: "-plugin-opt=O1"
+// O1-SAME: "--lto-CGO1"
 // O2-SAME: "-plugin-opt=O2"
+// O2-SAME: "--lto-CGO2"
 // O3-SAME: "-plugin-opt=O3"
+// 

[PATCH] D143109: [Sema] Push a LambdaScopeInfo before calling SubstDefaultArgument

2023-02-15 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added a comment.

@tahonermann @cor3ntin have you had a chance to take a look at the updated 
patch?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143109

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


[PATCH] D143921: [debug-info][codegen] Prevent creation of self-referential SP node

2023-02-15 Thread Felipe de Azevedo Piovezan via Phabricator via cfe-commits
fdeazeve updated this revision to Diff 497713.
fdeazeve added a comment.

Fixed clang format issue


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143921

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  llvm/docs/LangRef.rst
  llvm/lib/IR/Verifier.cpp
  llvm/test/Verifier/disubprogram_declaration.ll


Index: llvm/test/Verifier/disubprogram_declaration.ll
===
--- /dev/null
+++ llvm/test/Verifier/disubprogram_declaration.ll
@@ -0,0 +1,17 @@
+; RUN: llvm-as -disable-output <%s 2>&1| FileCheck %s
+
+declare !dbg !12 i32 @declared_only()
+
+!llvm.module.flags = !{!2}
+!llvm.dbg.cu = !{!5}
+
+!2 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus_14, file: !6, 
producer: "clang", emissionKind: FullDebug)
+!6 = !DIFile(filename: "a.cpp", directory: "/")
+!7 = !{}
+!11 = !DISubroutineType(types: !7)
+
+!12 = !DISubprogram(name: "declared_only", scope: !6, file: !6, line: 2, type: 
!11, spFlags: DISPFlagOptimized, retainedNodes: !7, declaration: !13)
+!13 = !DISubprogram(name: "declared_only", scope: !6, file: !6, line: 2, type: 
!11, spFlags: DISPFlagOptimized, retainedNodes: !7)
+; CHECK: subprogram declaration must not have a declaration field
+; CHECK: warning: ignoring invalid debug info
Index: llvm/lib/IR/Verifier.cpp
===
--- llvm/lib/IR/Verifier.cpp
+++ llvm/lib/IR/Verifier.cpp
@@ -1400,6 +1400,8 @@
   } else {
 // Subprogram declarations (part of the type hierarchy).
 CheckDI(!Unit, "subprogram declarations must not have a compile unit", &N);
+CheckDI(!N.getRawDeclaration(),
+"subprogram declaration must not have a declaration field");
   }
 
   if (auto *RawThrownTypes = N.getRawThrownTypes()) {
Index: llvm/docs/LangRef.rst
===
--- llvm/docs/LangRef.rst
+++ llvm/docs/LangRef.rst
@@ -5776,11 +5776,12 @@
 
 .. _DISubprogramDeclaration:
 
-When ``isDefinition: false``, subprograms describe a declaration in the type
-tree as opposed to a definition of a function.  If the scope is a composite
-type with an ODR ``identifier:`` and that does not set ``flags: DIFwdDecl``,
-then the subprogram declaration is uniqued based only on its ``linkageName:``
-and ``scope:``.
+When ``spFlags: DISPFlagDefinition`` is not present, subprograms describe a
+declaration in the type tree as opposed to a definition of a function. In this
+case, the ``declaration`` field must be empty. If the scope is a composite type
+with an ODR ``identifier:`` and that does not set ``flags: DIFwdDecl``, then
+the subprogram declaration is uniqued based only on its ``linkageName:`` and
+``scope:``.
 
 .. code-block:: text
 
@@ -5789,9 +5790,9 @@
 }
 
 !0 = distinct !DISubprogram(name: "foo", linkageName: "_Zfoov", scope: !1,
-file: !2, line: 7, type: !3, isLocal: true,
-isDefinition: true, scopeLine: 8,
-containingType: !4,
+file: !2, line: 7, type: !3,
+spFlags: DISPFlagDefinition | 
DISPFlagLocalToUnit,
+scopeLine: 8, containingType: !4,
 virtuality: DW_VIRTUALITY_pure_virtual,
 virtualIndex: 10, flags: DIFlagPrototyped,
 isOptimized: true, unit: !5, templateParams: 
!6,
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -4214,10 +4214,9 @@
 
   llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
   llvm::DISubroutineType *STy = getOrCreateFunctionType(D, FnType, Unit);
-  llvm::DISubprogram *SP =
-  DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo, STy,
-  ScopeLine, Flags, SPFlags, TParamsArray.get(),
-  getFunctionDeclaration(D), nullptr, Annotations);
+  llvm::DISubprogram *SP = DBuilder.createFunction(
+  FDContext, Name, LinkageName, Unit, LineNo, STy, ScopeLine, Flags,
+  SPFlags, TParamsArray.get(), nullptr, nullptr, Annotations);
 
   // Preserve btf_decl_tag attributes for parameters of extern functions
   // for BPF target. The parameters created in this loop are attached as


Index: llvm/test/Verifier/disubprogram_declaration.ll
===
--- /dev/null
+++ llvm/test/Verifier/disubprogram_declaration.ll
@@ -0,0 +1,17 @@
+; RUN: llvm-as -disable-output <%s 2>&1| FileCheck %s
+
+declare !dbg !12 i32 @declared_only()
+
+!llvm.module.flags = !{!2}
+!llvm.dbg.cu = !{!5}
+
+!2 = !{i32 2, !"Debug Info Version", i32 3}
+!5

[PATCH] D144115: [clang] Extend pragma dump to support expressions

2023-02-15 Thread Vlad Serebrennikov via Phabricator via cfe-commits
Endill created this revision.
Endill added reviewers: clang-language-wg, aaron.ballman.
Herald added a project: All.
Endill requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Extend `#pragma clang __debug dump` to support not only single identifier, but 
an expression as well. This makes it possible to test ADL and overload 
resolution directly, without being creative to make them observable via 
diagnostics (e.g. when over.match.best  
is involved). This implementation has a known limitation of not supporting 
dependent expressions properly, but it's quite useful even without such support.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144115

Files:
  clang/lib/Lex/Pragma.cpp
  clang/lib/Parse/ParsePragma.cpp


Index: clang/lib/Parse/ParsePragma.cpp
===
--- clang/lib/Parse/ParsePragma.cpp
+++ clang/lib/Parse/ParsePragma.cpp
@@ -13,6 +13,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/Basic/PragmaKinds.h"
 #include "clang/Basic/TargetInfo.h"
+#include "clang/Lex/LexDiagnostic.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/Token.h"
 #include "clang/Parse/LoopHint.h"
@@ -706,10 +707,27 @@
 
 void Parser::HandlePragmaDump() {
   assert(Tok.is(tok::annot_pragma_dump));
-  IdentifierInfo *II =
-  reinterpret_cast(Tok.getAnnotationValue());
-  Actions.ActOnPragmaDump(getCurScope(), Tok.getLocation(), II);
   ConsumeAnnotationToken();
+  if (Tok.is(tok::eod)) {
+PP.Diag(Tok, diag::warn_pragma_debug_missing_argument) << "dump";
+  } else if (NextToken().is(tok::eod)) {
+if (Tok.isNot(tok::identifier)) {
+  PP.Diag(Tok, diag::warn_pragma_debug_unexpected_argument);
+  ConsumeAnyToken();
+  ExpectAndConsume(tok::eod);
+  return;
+}
+IdentifierInfo *II = Tok.getIdentifierInfo();
+Actions.ActOnPragmaDump(getCurScope(), Tok.getLocation(), II);
+ConsumeToken();
+  } else {
+ExprResult E = ParseExpression();
+if (!E.isInvalid()) {
+  E.get()->dump();
+}
+SkipUntil(tok::eod, StopBeforeMatch);
+  }
+  ExpectAndConsume(tok::eod);
 }
 
 void Parser::HandlePragmaWeak() {
Index: clang/lib/Lex/Pragma.cpp
===
--- clang/lib/Lex/Pragma.cpp
+++ clang/lib/Lex/Pragma.cpp
@@ -1066,21 +1066,11 @@
 PP.EnterToken(Crasher, /*IsReinject*/ false);
   }
 } else if (II->isStr("dump")) {
-  Token Identifier;
-  PP.LexUnexpandedToken(Identifier);
-  if (auto *DumpII = Identifier.getIdentifierInfo()) {
-Token DumpAnnot;
-DumpAnnot.startToken();
-DumpAnnot.setKind(tok::annot_pragma_dump);
-DumpAnnot.setAnnotationRange(
-SourceRange(Tok.getLocation(), Identifier.getLocation()));
-DumpAnnot.setAnnotationValue(DumpII);
-PP.DiscardUntilEndOfDirective();
-PP.EnterToken(DumpAnnot, /*IsReinject*/false);
-  } else {
-PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
-<< II->getName();
-  }
+  Token DumpAnnot;
+  DumpAnnot.startToken();
+  DumpAnnot.setKind(tok::annot_pragma_dump);
+  DumpAnnot.setAnnotationRange(SourceRange(Tok.getLocation()));
+  PP.EnterToken(DumpAnnot, /*IsReinject*/false);
 } else if (II->isStr("diag_mapping")) {
   Token DiagName;
   PP.LexUnexpandedToken(DiagName);


Index: clang/lib/Parse/ParsePragma.cpp
===
--- clang/lib/Parse/ParsePragma.cpp
+++ clang/lib/Parse/ParsePragma.cpp
@@ -13,6 +13,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/Basic/PragmaKinds.h"
 #include "clang/Basic/TargetInfo.h"
+#include "clang/Lex/LexDiagnostic.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/Token.h"
 #include "clang/Parse/LoopHint.h"
@@ -706,10 +707,27 @@
 
 void Parser::HandlePragmaDump() {
   assert(Tok.is(tok::annot_pragma_dump));
-  IdentifierInfo *II =
-  reinterpret_cast(Tok.getAnnotationValue());
-  Actions.ActOnPragmaDump(getCurScope(), Tok.getLocation(), II);
   ConsumeAnnotationToken();
+  if (Tok.is(tok::eod)) {
+PP.Diag(Tok, diag::warn_pragma_debug_missing_argument) << "dump";
+  } else if (NextToken().is(tok::eod)) {
+if (Tok.isNot(tok::identifier)) {
+  PP.Diag(Tok, diag::warn_pragma_debug_unexpected_argument);
+  ConsumeAnyToken();
+  ExpectAndConsume(tok::eod);
+  return;
+}
+IdentifierInfo *II = Tok.getIdentifierInfo();
+Actions.ActOnPragmaDump(getCurScope(), Tok.getLocation(), II);
+ConsumeToken();
+  } else {
+ExprResult E = ParseExpression();
+if (!E.isInvalid()) {
+  E.get()->dump();
+}
+SkipUntil(tok::eod, StopBeforeMatch);
+  }
+  ExpectAndConsume(tok::eod);
 }
 
 void Parser::HandlePragmaWeak() {
Index: clang/lib/Lex/Pragma.cpp

[PATCH] D143849: [Clang][OpenCL] Allow pointers in structs as kernel arguments from 2.0

2023-02-15 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:9494
+  // of SVM.
+  if (S.getLangOpts().getOpenCLCompatibleVersion() > 120 &&
+  (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam))

Anastasia wrote:
> Ayal wrote:
> > Anastasia wrote:
> > > I think it should be possible to merge this with `if` below to avoid 
> > > condition duplication.
> > > 
> > > 
> > Sure, but that trades one duplication for another, rather than clearly 
> > separating the early-continue case early?
> > 
> > ```
> >   if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
> > if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
> >   continue;
> > S.Diag(Param->getLocation(),
> >diag::err_record_with_pointers_kernel_param)
> >   << PT->isUnionType()
> >   << PT;
> >   } else if (ParamType == InvalidAddrSpacePtrKernelParam) {
> > S.Diag(Param->getLocation(),
> >diag::err_record_with_pointers_kernel_param)
> >   << PT->isUnionType()
> >   << PT;
> >   } else {
> > S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
> > 
> > ```
> I am mainly thinking in terms of maintenance if for example someone fixes one 
> if and forgets another. Or if ifs will get separated by some other code and 
> then it is not easy to see that the same thing is handled differently in 
> OpenCL versions. 
> 
> Unfortunately we have a lot of those cases, I know this function has early 
> exists but it is not a common style.
> 
> 
> I was talking about something like:
> 
> 
> ```
> if (((S.getLangOpts().getOpenCLCompatibleVersion() <= 120) &&
> (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam)) ||
>   ParamType == InvalidAddrSpacePtrKernelParam)
> ```
> 
> It would also be ok to separate `InvalidAddrSpacePtrKernelParam` since it's 
> handling different feature.
Sorry I have forgotten that this part of the code is expected to handle the 
diagnostics only. The decision that the kernel parameter is wrong is done in 
`getOpenCLKernelParameterType`. I think you should alter the conditions there 
to check for OpenCL version and avoid classifying cases you care about as 
`PtrKernelParam` or `PtrPtrKernelParam`. Then here you wouldn't need this extra 
if/continue block. 


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

https://reviews.llvm.org/D143849

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


[PATCH] D142584: [CodeGen] Add a boolean flag to `Address::getPointer` and `Lvalue::getPointer` that indicates whether the pointer is known not to be null

2023-02-15 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak updated this revision to Diff 497719.
ahatanak added a comment.

Fix type and add comment. Remove unnecessary cast.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142584

Files:
  clang/lib/CodeGen/Address.h
  clang/lib/CodeGen/CGBuilder.h
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGClass.cpp
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CGException.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprCXX.cpp
  clang/lib/CodeGen/CGNonTrivialStruct.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGValue.h
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h

Index: clang/lib/CodeGen/CodeGenFunction.h
===
--- clang/lib/CodeGen/CodeGenFunction.h
+++ clang/lib/CodeGen/CodeGenFunction.h
@@ -3164,7 +3164,8 @@
 
 Address getIndirectAddress() const {
   assert(isIndirect());
-  return Address(Value, ElementType, CharUnits::fromQuantity(Alignment));
+  return Address(Value, ElementType, CharUnits::fromQuantity(Alignment),
+ KnownNonNull);
 }
   };
 
@@ -3771,8 +3772,13 @@
   /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
   /// variable length type, this is not possible.
   ///
-  LValue EmitLValue(const Expr *E);
+  LValue EmitLValue(const Expr *E,
+KnownNonNull_t IsKnownNonNull = NotKnownNonNull);
 
+private:
+  LValue EmitLValueHelper(const Expr *E, KnownNonNull_t IsKnownNonNull);
+
+public:
   /// Same as EmitLValue but additionally we generate checking code to
   /// guard against undefined behavior.  This is only suitable when we know
   /// that the address will be used to access the object.
@@ -4783,9 +4789,10 @@
   /// into the address of a local variable.  In such a case, it's quite
   /// reasonable to just ignore the returned alignment when it isn't from an
   /// explicit source.
-  Address EmitPointerWithAlignment(const Expr *Addr,
-   LValueBaseInfo *BaseInfo = nullptr,
-   TBAAAccessInfo *TBAAInfo = nullptr);
+  Address
+  EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo = nullptr,
+   TBAAAccessInfo *TBAAInfo = nullptr,
+   KnownNonNull_t IsKnownNonNull = NotKnownNonNull);
 
   /// If \p E references a parameter with pass_object_size info or a constant
   /// array size modifier, emit the object size divided by the size of \p EltTy.
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -1104,8 +1104,9 @@
 auto AI = CurFn->arg_begin();
 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
   ++AI;
-ReturnValue = Address(&*AI, ConvertType(RetTy),
-  CurFnInfo->getReturnInfo().getIndirectAlign());
+ReturnValue =
+Address(&*AI, ConvertType(RetTy),
+CurFnInfo->getReturnInfo().getIndirectAlign(), KnownNonNull);
 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
   ReturnValuePointer =
   CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
@@ -1125,8 +1126,8 @@
 cast(Addr)->getResultElementType();
 ReturnValuePointer = Address(Addr, Ty, getPointerAlign());
 Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
-ReturnValue =
-Address(Addr, ConvertType(RetTy), CGM.getNaturalTypeAlignment(RetTy));
+ReturnValue = Address(Addr, ConvertType(RetTy),
+  CGM.getNaturalTypeAlignment(RetTy), KnownNonNull);
   } else {
 ReturnValue = CreateIRTemp(RetTy, "retval");
 
Index: clang/lib/CodeGen/CGValue.h
===
--- clang/lib/CodeGen/CGValue.h
+++ clang/lib/CodeGen/CGValue.h
@@ -225,6 +225,9 @@
   // this lvalue.
   bool Nontemporal : 1;
 
+  // The pointer is known not to be null.
+  bool IsKnownNonNull : 1;
+
   LValueBaseInfo BaseInfo;
   TBAAAccessInfo TBAAInfo;
 
@@ -333,24 +336,35 @@
   LValueBaseInfo getBaseInfo() const { return BaseInfo; }
   void setBaseInfo(LValueBaseInfo Info) { BaseInfo = Info; }
 
+  KnownNonNull_t isKnownNonNull() const {
+return (KnownNonNull_t)IsKnownNonNull;
+  }
+  LValue setKnownNonNull() {
+IsKnownNonNull = true;
+return *this;
+  }
+
   // simple lvalue
   llvm::Value *getPointer(CodeGenFunction &CGF) const {
 assert(isSimple());
 return V;
   }
   Address getAddress(CodeGenFunction &CGF) const {
-return Address(getPointer(CGF), ElementType, getAlignment());
+return Address(getPointer(CGF), ElementType, getAlignment(),
+   isKnownNonNull());
   }
   void setAddress(Address address) {
 assert(isSimple());
 V = address.getPointe

[PATCH] D144036: [clang-tidy] Add bugprone-enum-to-bool-conversion check

2023-02-15 Thread Piotr Zegar via Phabricator via cfe-commits
ClockMan updated this revision to Diff 497727.
ClockMan marked 3 inline comments as done.
ClockMan added a comment.

Corrected issues mentioned in review


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144036

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/EnumToBoolConversionCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/EnumToBoolConversionCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/bugprone/enum-to-bool-conversion.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion-cpp11.cpp
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion.cpp
@@ -0,0 +1,119 @@
+// RUN: %check_clang_tidy -std=c++98-or-later %s bugprone-enum-to-bool-conversion %t -- \
+// RUN:   -config="{CheckOptions: [{key: bugprone-enum-to-bool-conversion.EnumIgnoreRegexp, value: '^::without::issue::IgnoredEnum$'}]}"
+
+namespace with::issue
+{
+
+typedef enum EStatus
+{
+SUCCESS   = 1,
+FAILURE   = 2,
+INVALID_PARAM = 3,
+UNKNOWN   = 4
+} Status;
+
+bool testEnumConversion(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:12: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return value;
+}
+
+bool testTypedefConversion(Status value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:12: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return value;
+}
+
+bool testExplicitConversion(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:30: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return static_cast(value);
+}
+
+bool testInIfConversion(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:9: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+if (value)
+{
+return false;
+}
+
+return true;
+}
+
+bool testWithNegation(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:16: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return not value;
+}
+
+}
+
+namespace without::issue
+{
+
+enum StatusWithZero
+{
+UNK  = 0,
+OK   = 1,
+NOT_OK = 2
+};
+
+bool testEnumConversion(StatusWithZero value)
+{
+return value;
+}
+
+enum WithDefault
+{
+Value0,
+Value1
+};
+
+bool testEnumConversion(WithDefault value)
+{
+return value;
+}
+
+enum WithNegative : int
+{
+Nen2 = -2,
+Nen1,
+Nen0
+};
+
+bool testEnumConversion(WithNegative value)
+{
+return value;
+}
+
+enum EStatus
+{
+SUCCESS = 1,
+FAILURE,
+INVALID_PARAM,
+UNKNOWN
+};
+
+bool explicitCompare(EStatus value)
+{
+return value == SUCCESS;
+}
+
+bool testEnumeratorCompare()
+{
+return SUCCESS;
+}
+
+enum IgnoredEnum
+{
+IGNORED_VALUE_1 = 1,
+IGNORED_VALUE_2
+};
+
+bool testIgnored(IgnoredEnum value)
+{
+return value;
+}
+
+}
Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion-cpp11.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion-cpp11.cpp
@@ -0,0 +1,32 @@
+// RUN: %check_clang_tidy -std=c++11-or-later %s bugprone-enum-to-bool-conversion %t
+
+namespace with::issue
+{
+
+enum class EStatus : char
+{
+SUCCESS   = 1,
+FAILURE   = 2,
+INVALID_PARAM = 3,
+UNKNOWN   = 4
+};
+
+bool testEnumConversion(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:12: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return static_cast(value);
+}
+
+enum EResult : short
+{
+OK = 1,
+NOT_OK
+};
+
+bool testEnumConversion(const EResult& value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:12: warning: conversion of 'EResult' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return value;
+}
+
+}
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy

[PATCH] D144036: [clang-tidy] Add bugprone-enum-to-bool-conversion check

2023-02-15 Thread Piotr Zegar via Phabricator via cfe-commits
ClockMan added a comment.

Fixed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144036

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


[clang] 57865bc - [CodeGen] Add a flag to `Address` and `Lvalue` that is used to keep

2023-02-15 Thread Akira Hatanaka via cfe-commits

Author: Akira Hatanaka
Date: 2023-02-15T10:15:13-08:00
New Revision: 57865bc5ad277166507d9e9fbb5205be86caa73a

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

LOG: [CodeGen] Add a flag to `Address` and `Lvalue` that is used to keep
track of whether the pointer is known not to be null

The flag will be used for the arm64e work we plan to upstream in the
future (see https://lists.llvm.org/pipermail/llvm-dev/2019-October/136091.html).
Currently the flag has no effect on code generation.

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

Added: 


Modified: 
clang/lib/CodeGen/Address.h
clang/lib/CodeGen/CGBuilder.h
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGClass.cpp
clang/lib/CodeGen/CGDecl.cpp
clang/lib/CodeGen/CGException.cpp
clang/lib/CodeGen/CGExpr.cpp
clang/lib/CodeGen/CGExprCXX.cpp
clang/lib/CodeGen/CGNonTrivialStruct.cpp
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGValue.h
clang/lib/CodeGen/CodeGenFunction.cpp
clang/lib/CodeGen/CodeGenFunction.h

Removed: 




diff  --git a/clang/lib/CodeGen/Address.h b/clang/lib/CodeGen/Address.h
index bddeac1d6dcbd..9f7cd17752121 100644
--- a/clang/lib/CodeGen/Address.h
+++ b/clang/lib/CodeGen/Address.h
@@ -22,52 +22,69 @@
 namespace clang {
 namespace CodeGen {
 
+// Indicates whether a pointer is known not to be null.
+enum KnownNonNull_t { NotKnownNonNull, KnownNonNull };
+
 // We try to save some space by using 6 bits over two PointerIntPairs to store
 // the alignment. However, some arches don't support 3 bits in a PointerIntPair
 // so we fallback to storing the alignment separately.
 template = 8> class AddressImpl {};
 
 template  class AddressImpl {
-  llvm::Value *Pointer;
+  llvm::PointerIntPair PointerAndKnownNonNull;
   llvm::Type *ElementType;
   CharUnits Alignment;
 
 public:
   AddressImpl(llvm::Value *Pointer, llvm::Type *ElementType,
-  CharUnits Alignment)
-  : Pointer(Pointer), ElementType(ElementType), Alignment(Alignment) {}
-  llvm::Value *getPointer() const { return Pointer; }
+  CharUnits Alignment, KnownNonNull_t IsKnownNonNull)
+  : PointerAndKnownNonNull(Pointer, IsKnownNonNull),
+ElementType(ElementType), Alignment(Alignment) {}
+  llvm::Value *getPointer() const {
+return PointerAndKnownNonNull.getPointer();
+  }
   llvm::Type *getElementType() const { return ElementType; }
   CharUnits getAlignment() const { return Alignment; }
+  KnownNonNull_t isKnownNonNull() const {
+return (KnownNonNull_t)PointerAndKnownNonNull.getInt();
+  }
+  void setKnownNonNull() { PointerAndKnownNonNull.setInt(true); }
 };
 
 template  class AddressImpl {
-  // Int portion stores upper 3 bits of the log of the alignment.
+  // Int portion stores the non-null bit and the upper 2 bits of the log of the
+  // alignment.
   llvm::PointerIntPair Pointer;
   // Int portion stores lower 3 bits of the log of the alignment.
   llvm::PointerIntPair ElementType;
 
 public:
   AddressImpl(llvm::Value *Pointer, llvm::Type *ElementType,
-  CharUnits Alignment)
+  CharUnits Alignment, KnownNonNull_t IsKnownNonNull)
   : Pointer(Pointer), ElementType(ElementType) {
-if (Alignment.isZero())
+if (Alignment.isZero()) {
+  this->Pointer.setInt(IsKnownNonNull << 2);
   return;
-// Currently the max supported alignment is much less than 1 << 63 and is
+}
+// Currently the max supported alignment is exactly 1 << 32 and is
 // guaranteed to be a power of 2, so we can store the log of the alignment
-// into 6 bits.
+// into 5 bits.
 assert(Alignment.isPowerOfTwo() && "Alignment cannot be zero");
 auto AlignLog = llvm::Log2_64(Alignment.getQuantity());
-assert(AlignLog < (1 << 6) && "cannot fit alignment into 6 bits");
-this->Pointer.setInt(AlignLog >> 3);
+assert(AlignLog < (1 << 5) && "cannot fit alignment into 5 bits");
+this->Pointer.setInt(IsKnownNonNull << 2 | AlignLog >> 3);
 this->ElementType.setInt(AlignLog & 7);
   }
   llvm::Value *getPointer() const { return Pointer.getPointer(); }
   llvm::Type *getElementType() const { return ElementType.getPointer(); }
   CharUnits getAlignment() const {
-unsigned AlignLog = (Pointer.getInt() << 3) | ElementType.getInt();
+unsigned AlignLog = ((Pointer.getInt() & 0x3) << 3) | ElementType.getInt();
 return CharUnits::fromQuantity(CharUnits::QuantityType(1) << AlignLog);
   }
+  KnownNonNull_t isKnownNonNull() const {
+return (KnownNonNull_t)(!!(Pointer.getInt() & 0x4));
+  }
+  void setKnownNonNull() { Pointer.setInt(Pointer.getInt() | 0x4); }
 };
 
 /// An aligned address.
@@ -75,11 +92,13 @@ class Address {
   AddressImpl A;
 
 protected:
-  Address(std::nullptr_t) : A(nullpt

[PATCH] D142584: [CodeGen] Add a boolean flag to `Address::getPointer` and `Lvalue::getPointer` that indicates whether the pointer is known not to be null

2023-02-15 Thread Akira Hatanaka via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG57865bc5ad27: [CodeGen] Add a flag to `Address` and `Lvalue` 
that is used to keep (authored by ahatanak).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142584

Files:
  clang/lib/CodeGen/Address.h
  clang/lib/CodeGen/CGBuilder.h
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGClass.cpp
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CGException.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprCXX.cpp
  clang/lib/CodeGen/CGNonTrivialStruct.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGValue.h
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h

Index: clang/lib/CodeGen/CodeGenFunction.h
===
--- clang/lib/CodeGen/CodeGenFunction.h
+++ clang/lib/CodeGen/CodeGenFunction.h
@@ -3164,7 +3164,8 @@
 
 Address getIndirectAddress() const {
   assert(isIndirect());
-  return Address(Value, ElementType, CharUnits::fromQuantity(Alignment));
+  return Address(Value, ElementType, CharUnits::fromQuantity(Alignment),
+ KnownNonNull);
 }
   };
 
@@ -3771,8 +3772,13 @@
   /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
   /// variable length type, this is not possible.
   ///
-  LValue EmitLValue(const Expr *E);
+  LValue EmitLValue(const Expr *E,
+KnownNonNull_t IsKnownNonNull = NotKnownNonNull);
 
+private:
+  LValue EmitLValueHelper(const Expr *E, KnownNonNull_t IsKnownNonNull);
+
+public:
   /// Same as EmitLValue but additionally we generate checking code to
   /// guard against undefined behavior.  This is only suitable when we know
   /// that the address will be used to access the object.
@@ -4783,9 +4789,10 @@
   /// into the address of a local variable.  In such a case, it's quite
   /// reasonable to just ignore the returned alignment when it isn't from an
   /// explicit source.
-  Address EmitPointerWithAlignment(const Expr *Addr,
-   LValueBaseInfo *BaseInfo = nullptr,
-   TBAAAccessInfo *TBAAInfo = nullptr);
+  Address
+  EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo = nullptr,
+   TBAAAccessInfo *TBAAInfo = nullptr,
+   KnownNonNull_t IsKnownNonNull = NotKnownNonNull);
 
   /// If \p E references a parameter with pass_object_size info or a constant
   /// array size modifier, emit the object size divided by the size of \p EltTy.
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -1104,8 +1104,9 @@
 auto AI = CurFn->arg_begin();
 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
   ++AI;
-ReturnValue = Address(&*AI, ConvertType(RetTy),
-  CurFnInfo->getReturnInfo().getIndirectAlign());
+ReturnValue =
+Address(&*AI, ConvertType(RetTy),
+CurFnInfo->getReturnInfo().getIndirectAlign(), KnownNonNull);
 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
   ReturnValuePointer =
   CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
@@ -1125,8 +1126,8 @@
 cast(Addr)->getResultElementType();
 ReturnValuePointer = Address(Addr, Ty, getPointerAlign());
 Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
-ReturnValue =
-Address(Addr, ConvertType(RetTy), CGM.getNaturalTypeAlignment(RetTy));
+ReturnValue = Address(Addr, ConvertType(RetTy),
+  CGM.getNaturalTypeAlignment(RetTy), KnownNonNull);
   } else {
 ReturnValue = CreateIRTemp(RetTy, "retval");
 
Index: clang/lib/CodeGen/CGValue.h
===
--- clang/lib/CodeGen/CGValue.h
+++ clang/lib/CodeGen/CGValue.h
@@ -225,6 +225,9 @@
   // this lvalue.
   bool Nontemporal : 1;
 
+  // The pointer is known not to be null.
+  bool IsKnownNonNull : 1;
+
   LValueBaseInfo BaseInfo;
   TBAAAccessInfo TBAAInfo;
 
@@ -333,24 +336,35 @@
   LValueBaseInfo getBaseInfo() const { return BaseInfo; }
   void setBaseInfo(LValueBaseInfo Info) { BaseInfo = Info; }
 
+  KnownNonNull_t isKnownNonNull() const {
+return (KnownNonNull_t)IsKnownNonNull;
+  }
+  LValue setKnownNonNull() {
+IsKnownNonNull = true;
+return *this;
+  }
+
   // simple lvalue
   llvm::Value *getPointer(CodeGenFunction &CGF) const {
 assert(isSimple());
 return V;
   }
   Address getAddress(CodeGenFunction &CGF) const {
-return Address(getPointer(CGF), ElementType, getAlignment());
+return Address(getPointer(CGF), ElementType, getAlignment(),
+  

[PATCH] D144120: [HLSL] add log library functions This change exposes the log library functions for HLSL, excluding long, int, and long long doubles. The log functions are supported for all scalar, ve

2023-02-15 Thread Joshua Batista via Phabricator via cfe-commits
bob80905 created this revision.
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.

...missing in this patch because those types
don't exist in HLSL. Int is missing because the log functions only work on 
floating type arguments.

The full documentation of the HLSL log functions are available here:
https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-log
https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-log2
https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-log10


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144120

Files:
  clang/lib/Headers/hlsl/hlsl_intrinsics.h
  clang/test/CodeGenHLSL/builtins/log.hlsl
  clang/test/CodeGenHLSL/builtins/log10.hlsl
  clang/test/CodeGenHLSL/builtins/log2.hlsl

Index: clang/test/CodeGenHLSL/builtins/log2.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/builtins/log2.hlsl
@@ -0,0 +1,56 @@
+// 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
+
+// CHECK: define noundef half @
+// CHECK: call half @llvm.log2.f16(
+// NO_HALF: define noundef float @"?test_log2_half@@YA$halff@$halff@@Z"(
+// NO_HALF: call float @llvm.log2.f32(
+half test_log2_half ( half p0 ) {
+  return log2 ( p0 );
+}
+// CHECK: define noundef <2 x half> @
+// CHECK: call <2 x half> @llvm.log2.v2f16
+// NO_HALF: define noundef <2 x float> @"?test_log2_float2@@YAT?$__vector@M$01@__clang@@T12@@Z"(
+// NO_HALF: call <2 x float> @llvm.log2.v2f32(
+half2 test_log2_half2 ( half2 p0 ) {
+  return log2 ( p0 );
+}
+// CHECK: define noundef <3 x half> @
+// CHECK: call <3 x half> @llvm.log2.v3f16
+// NO_HALF: define noundef <3 x float> @"?test_log2_float3@@YAT?$__vector@M$02@__clang@@T12@@Z"(
+// NO_HALF: call <3 x float> @llvm.log2.v3f32(
+half3 test_log2_half3 ( half3 p0 ) {
+  return log2 ( p0 );
+}
+// CHECK: define noundef <4 x half> @
+// CHECK: call <4 x half> @llvm.log2.v4f16
+// NO_HALF: define noundef <4 x float> @"?test_log2_float4@@YAT?$__vector@M$03@__clang@@T12@@Z"(
+// NO_HALF: call <4 x float> @llvm.log2.v4f32(
+half4 test_log2_half4 ( half4 p0 ) {
+  return log2 ( p0 );
+}
+
+// CHECK: define noundef float @
+// CHECK: call float @llvm.log2.f32(
+float test_log2_float ( float p0 ) {
+  return log2 ( p0 );
+}
+// CHECK: define noundef <2 x float> @
+// CHECK: call <2 x float> @llvm.log2.v2f32
+float2 test_log2_float2 ( float2 p0 ) {
+  return log2 ( p0 );
+}
+// CHECK: define noundef <3 x float> @
+// CHECK: call <3 x float> @llvm.log2.v3f32
+float3 test_log2_float3 ( float3 p0 ) {
+  return log2 ( p0 );
+}
+// CHECK: define noundef <4 x float> @
+// CHECK: call <4 x float> @llvm.log2.v4f32
+float4 test_log2_float4 ( float4 p0 ) {
+  return log2 ( p0 );
+}
\ No newline at end of file
Index: clang/test/CodeGenHLSL/builtins/log10.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/builtins/log10.hlsl
@@ -0,0 +1,56 @@
+// 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
+
+// CHECK: define noundef half @
+// CHECK: call half @llvm.log10.f16(
+// NO_HALF: define noundef float @"?test_log10_half@@YA$halff@$halff@@Z"(
+// NO_HALF: call float @llvm.log10.f32(
+half test_log10_half ( half p0 ) {
+  return log10 ( p0 );
+}
+// CHECK: define noundef <2 x half> @
+// CHECK: call <2 x half> @llvm.log10.v2f16
+// NO_HALF: define noundef <2 x float> @"?test_log10_float2@@YAT?$__vector@M$01@__clang@@T12@@Z"(
+// NO_HALF: call <2 x float> @llvm.log10.v2f32(
+half2 test_log10_half2 ( half2 p0 ) {
+  return log10 ( p0 );
+}
+// CHECK: define noundef <3 x half> @
+// CHECK: call <3 x half> @llvm.log10.v3f16
+// NO_HALF: define noundef <3 x float> @"?test_log10_float3@@YAT?$__vector@M$02@__clang@@T12@@Z"(
+// NO_HALF: call <3 x float> @llvm.log10.v3f32(
+half3 test_log10_half3 ( half3 p0 ) {
+  return log10 ( p0 );
+}
+// CHECK: define noundef <4 x half> @
+// CHECK: call <4 x half> @llvm.log10.v4f16
+// NO_HALF: define noundef <4 x float> @"?test_log10_float4@@YAT?$__vector@M$03@__clang@@T12@@Z"(
+// NO_HA

[PATCH] D109239: Add support for floating-option `-ffp-eval-method` and for new `pragma clang fp eval-method`

2023-02-15 Thread Dave Green via Phabricator via cfe-commits
dmgreen added a comment.

Hi. I created this issue about the use of Ofast and -1:
https://github.com/llvm/llvm-project/issues/60781


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

https://reviews.llvm.org/D109239

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


[PATCH] D109239: Add support for floating-option `-ffp-eval-method` and for new `pragma clang fp eval-method`

2023-02-15 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added a comment.

In D109239#4129733 , @dmgreen wrote:

> Hi. I created this issue about the use of Ofast and -1:
> https://github.com/llvm/llvm-project/issues/60781

Thanks. Will take a look.


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

https://reviews.llvm.org/D109239

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


[PATCH] D142507: [AMDGPU] Split dot7 feature

2023-02-15 Thread Stanislav Mekhanoshin via Phabricator via cfe-commits
rampitec added a comment.

In D142507#4127505 , @b-sumner wrote:

>> My current understanding is the c-p will go into already forked clang-16, 
>> but not to rocm 5.4. So rocm device-libs will be accompanied by the older 
>> clang-16 w/o this and stay compatible. Someone building from scratch will 
>> use latest clang-16 and staging device-libs with this change. Do you think 
>> this will work?
>
> I wouldn't recommend it.  I would patch whatever device libs are being built 
> in association with clang-16, not staging.  Staging device libs is only 
> appropriate for the staging compiler.  A hash of device libs from around the 
> time that clang-16 stable released would probably be safe.

In general the idea is that compiler and device-libs should match. I guess the 
correct answer then users of clang-16 shall use rocm-5.4.x branch of the device 
libs?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142507

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


[clang] a9797d7 - [C2x] Implement the `unreachable` macro for WG14 N2826

2023-02-15 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2023-02-15T14:43:01-05:00
New Revision: a9797d7d2d7878464868312e0c147b4e747a31c6

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

LOG: [C2x] Implement the `unreachable` macro for WG14 N2826

This exposes __builtin_unreachable as the expansion for the unreachable
macro in C2x. I added this definition under __need_STDDEF_H_misc on the
assumption there is no need for a separate need macro to control adding
this.

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

Added: 
clang/test/C/C2x/n2826.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Headers/stddef.h
clang/www/c_status.html

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0dcd9b9f04b1d..ab7518cc2dc6b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -124,6 +124,8 @@ C Language Changes in Clang
 
 C2x Feature Support
 ---
+- Implemented the ``unreachable`` macro in freestanding  for
+  `WG14 N2826 `_
 
 C++ Language Changes in Clang
 -

diff  --git a/clang/lib/Headers/stddef.h b/clang/lib/Headers/stddef.h
index 42815176dcd0f..539541f0ed41a 100644
--- a/clang/lib/Headers/stddef.h
+++ b/clang/lib/Headers/stddef.h
@@ -103,6 +103,11 @@ using ::std::nullptr_t;
 typedef typeof(nullptr) nullptr_t;
 #endif /* defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202000L */
 
+#if defined(__need_STDDEF_H_misc) && defined(__STDC_VERSION__) &&  
\
+__STDC_VERSION__ >= 202000L
+#define unreachable() __builtin_unreachable()
+#endif /* defined(__need_STDDEF_H_misc) && >= C23 */
+
 #if defined(__need_STDDEF_H_misc)
 #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) ||  
\
 (defined(__cplusplus) && __cplusplus >= 201103L)

diff  --git a/clang/test/C/C2x/n2826.c b/clang/test/C/C2x/n2826.c
new file mode 100644
index 0..f108985c13ddd
--- /dev/null
+++ b/clang/test/C/C2x/n2826.c
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -ffreestanding -emit-llvm -o - -std=c2x %s | FileCheck %s
+// RUN: %clang_cc1 -ffreestanding -std=c17 -verify %s
+
+/* WG14 N2826: Clang 17
+ * Add annotations for unreachable control flow v2
+ */
+#include 
+
+enum E {
+  Zero,
+  One,
+  Two,
+};
+
+int test(enum E e) {
+  switch (e) {
+  case Zero: return 0;
+  case One: return 1;
+  case Two: return 2;
+  }
+  unreachable(); // expected-error {{call to undeclared function 
'unreachable'}}
+}
+
+// CHECK: switch i32 %0, label %[[EPILOG:.+]] [
+// CHECK: [[EPILOG]]:
+// CHECK-NEXT: unreachable

diff  --git a/clang/www/c_status.html b/clang/www/c_status.html
index 741d8c5b1ad9c..ee0f116bc2908 100644
--- a/clang/www/c_status.html
+++ b/clang/www/c_status.html
@@ -1028,7 +1028,7 @@ C2x implementation status
 
   Add annotations for unreachable control flow v2
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2826.pdf";>N2826
-  No
+  Clang 17
 
 
   Unicode Sequences More Than 21 Bits are a Constraint Violation 
r0



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


[PATCH] D143430: [C2x] Implement the `unreachable` macro for WG14 N2826

2023-02-15 Thread Aaron Ballman via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa9797d7d2d78: [C2x] Implement the `unreachable` macro for 
WG14 N2826 (authored by aaron.ballman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143430

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Headers/stddef.h
  clang/test/C/C2x/n2826.c
  clang/www/c_status.html


Index: clang/www/c_status.html
===
--- clang/www/c_status.html
+++ clang/www/c_status.html
@@ -1028,7 +1028,7 @@
 
   Add annotations for unreachable control flow v2
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2826.pdf";>N2826
-  No
+  Clang 17
 
 
   Unicode Sequences More Than 21 Bits are a Constraint Violation 
r0
Index: clang/test/C/C2x/n2826.c
===
--- /dev/null
+++ clang/test/C/C2x/n2826.c
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -ffreestanding -emit-llvm -o - -std=c2x %s | FileCheck %s
+// RUN: %clang_cc1 -ffreestanding -std=c17 -verify %s
+
+/* WG14 N2826: Clang 17
+ * Add annotations for unreachable control flow v2
+ */
+#include 
+
+enum E {
+  Zero,
+  One,
+  Two,
+};
+
+int test(enum E e) {
+  switch (e) {
+  case Zero: return 0;
+  case One: return 1;
+  case Two: return 2;
+  }
+  unreachable(); // expected-error {{call to undeclared function 
'unreachable'}}
+}
+
+// CHECK: switch i32 %0, label %[[EPILOG:.+]] [
+// CHECK: [[EPILOG]]:
+// CHECK-NEXT: unreachable
Index: clang/lib/Headers/stddef.h
===
--- clang/lib/Headers/stddef.h
+++ clang/lib/Headers/stddef.h
@@ -103,6 +103,11 @@
 typedef typeof(nullptr) nullptr_t;
 #endif /* defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202000L */
 
+#if defined(__need_STDDEF_H_misc) && defined(__STDC_VERSION__) &&  
\
+__STDC_VERSION__ >= 202000L
+#define unreachable() __builtin_unreachable()
+#endif /* defined(__need_STDDEF_H_misc) && >= C23 */
+
 #if defined(__need_STDDEF_H_misc)
 #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) ||  
\
 (defined(__cplusplus) && __cplusplus >= 201103L)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -124,6 +124,8 @@
 
 C2x Feature Support
 ---
+- Implemented the ``unreachable`` macro in freestanding  for
+  `WG14 N2826 `_
 
 C++ Language Changes in Clang
 -


Index: clang/www/c_status.html
===
--- clang/www/c_status.html
+++ clang/www/c_status.html
@@ -1028,7 +1028,7 @@
 
   Add annotations for unreachable control flow v2
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2826.pdf";>N2826
-  No
+  Clang 17
 
 
   Unicode Sequences More Than 21 Bits are a Constraint Violation r0
Index: clang/test/C/C2x/n2826.c
===
--- /dev/null
+++ clang/test/C/C2x/n2826.c
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -ffreestanding -emit-llvm -o - -std=c2x %s | FileCheck %s
+// RUN: %clang_cc1 -ffreestanding -std=c17 -verify %s
+
+/* WG14 N2826: Clang 17
+ * Add annotations for unreachable control flow v2
+ */
+#include 
+
+enum E {
+  Zero,
+  One,
+  Two,
+};
+
+int test(enum E e) {
+  switch (e) {
+  case Zero: return 0;
+  case One: return 1;
+  case Two: return 2;
+  }
+  unreachable(); // expected-error {{call to undeclared function 'unreachable'}}
+}
+
+// CHECK: switch i32 %0, label %[[EPILOG:.+]] [
+// CHECK: [[EPILOG]]:
+// CHECK-NEXT: unreachable
Index: clang/lib/Headers/stddef.h
===
--- clang/lib/Headers/stddef.h
+++ clang/lib/Headers/stddef.h
@@ -103,6 +103,11 @@
 typedef typeof(nullptr) nullptr_t;
 #endif /* defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202000L */
 
+#if defined(__need_STDDEF_H_misc) && defined(__STDC_VERSION__) &&  \
+__STDC_VERSION__ >= 202000L
+#define unreachable() __builtin_unreachable()
+#endif /* defined(__need_STDDEF_H_misc) && >= C23 */
+
 #if defined(__need_STDDEF_H_misc)
 #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) ||  \
 (defined(__cplusplus) && __cplusplus >= 201103L)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -124,6 +124,8 @@
 
 C2x Feature Support
 ---
+- Implemented the ``unreachable`` macro in freestanding  for
+  `WG14 N2826 `_
 
 C++ Language Changes in Clang
 -

[PATCH] D143691: Fix clang-formats IncludeCategory to match the documentation

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

Looks good to me, apart from that one issue.




Comment at: clang/lib/Tooling/Inclusions/IncludeStyle.cpp:23
+
+constexpr int DefaultPriority = std::numeric_limits::max();
+

Please move this into the `mapping` function.



Comment at: clang/unittests/Format/SortIncludesTest.cpp:11
 #include "clang/Format/Format.h"
+#include "clang/Tooling/Inclusions/IncludeStyle.h"
 #include "llvm/ADT/StringRef.h"

Don't need that, or?



Comment at: clang/unittests/Format/SortIncludesTest.cpp:548
+  EXPECT_EQ("#include \"a.h\"\n"
+"#include \"llvm/a.h\"\n"
+"#include \"b.h\"\n"

While I may accept there are more than one //main// header, this should not 
happen in my opinion.



Comment at: clang/unittests/Format/SortIncludesTest.cpp:557
+
+  // Keep manually splitted groups in place
   EXPECT_EQ("#include \"a.h\"\n"

End comments with full stop.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143691

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


[PATCH] D140756: Add clang_CXXMethod_isExplicit to libclang

2023-02-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D140756#4128729 , @diseraluca 
wrote:

> In D140756#4100387 , @aaron.ballman 
> wrote:
>
>> @diseraluca -- do you need this cherry picked into Clang 16 or are you fine 
>> if this goes into Clang 17 instead?
>
> Sorry for checking in so late, I noticed the notifications only now. We are 
> using a different solution for the time being so it is correct that this is 
> fine being in Clang 17.
>
> Thank you for taking care of this.

Thank you for the info!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140756

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


[PATCH] D143418: [libclang] Add API to set preferred temp dir path

2023-02-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D143418#4126266 , @vedgy wrote:

> `size_t` indeed makes logical sense for this member as that's the return type 
> of `sizeof`. `size_t` is two times larger than `unsigned` on x86_64, but I 
> don't think the size of this struct has any chance of impacting performance.

Agreed.

> Though it wouldn't hurt to pack the size and the boolean options in a 
> single-pointer-sized region on x86_64. After all, this struct's size will 
> never reach `UINT_MAX`. I slightly prefer `unsigned` due to my efficiency 
> inclinations :). What do you prefer? Is there any benefit in using a 
> fixed-size integer type here?

I've been trying to think of benefits for using a fixed-size integer type and 
the closest I can come is the consistency of the structure size across targets, 
but I don't think we need that consistency. I don't have a strong preference 
for `unsigned` vs `size_t`, so how about we go with your slight preference for 
`unsigned` unless someone finds a reason to use something else?

>>> 2. Should `int excludeDeclarationsFromPCH` and `int displayDiagnostics` 
>>> currently passed to `clang_createIndex()` also be included in the struct? 
>>> Then only a single argument will be passed to 
>>> `clang_createIndexWithOptions()`: `CXIndexOptions`.
>>
>> I think that makes sense to me. It does raise the question of whether we 
>> want to pack these boolean-like fields together, as in:
>>
>>   struct CXIndexOptions {
>> size_t Size;
>>   
>> int ExcludeDeclsFromPCH : 1;
>> int DisplayDiagnostics : 1;
>> int Reserved : 30;
>>   
>> const char *PreambleStoragePath;
>> ...
>>   };
>>
>> This makes it a little less likely to need to grow the structure when adding 
>> new options.
>
> When we add new options, the struct's size must grow in order to distinguish 
> different struct versions and prevent undefined behavior!

Oh gosh you're absolutely right, that was a think-o on my part.

> OK, let's skip the global options member for now. I'll add a `\todo` about 
> this.

SGTM, thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143418

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


[PATCH] D144016: [Sema] Relax a failing assertion in TransformBlockExpr

2023-02-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Precommit CI found an issue on Windows that should be addressed:

  FAIL: Clang :: CodeGenCXX/cxx1z-constexpr-if.cpp (7014 of 17903)
   TEST 'Clang :: CodeGenCXX/cxx1z-constexpr-if.cpp' FAILED 

  Script:
  --
  : 'RUN: at line 1';   
c:\ws\w32-1\llvm-project\premerge-checks\build\bin\clang.exe -cc1 
-internal-isystem 
c:\ws\w32-1\llvm-project\premerge-checks\build\lib\clang\17\include 
-nostdsysteminc -std=c++1z 
C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp
 -emit-llvm -fblocks -o - | 
c:\ws\w32-1\llvm-project\premerge-checks\build\bin\filecheck.exe 
C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp
 --implicit-check-not=should_not_be_used
  --
  Exit Code: 1
  
  Command Output (stdout):
  --
  $ ":" "RUN: at line 1"
  $ "c:\ws\w32-1\llvm-project\premerge-checks\build\bin\clang.exe" "-cc1" 
"-internal-isystem" 
"c:\ws\w32-1\llvm-project\premerge-checks\build\lib\clang\17\include" 
"-nostdsysteminc" "-std=c++1z" 
"C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp"
 "-emit-llvm" "-fblocks" "-o" "-"
  $ "c:\ws\w32-1\llvm-project\premerge-checks\build\bin\filecheck.exe" 
"C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp"
 "--implicit-check-not=should_not_be_used"
  # command stderr:
  
C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp:50:17:
 error: CHECK-LABEL: expected string not found in input
  // CHECK-LABEL: define internal void 
@___ZN16BlockThisCapture1S1mILb0EEEvv_block_invoke(
  ^
  :1:1: note: scanning from here
  ; ModuleID = 
'C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp'
  ^
  :53:1: note: possible intended match here
  define internal void 
@"__??$m@$0A@@S@BlockThisCapture@@QEAAXXZ_block_invoke"(ptr noundef 
%.block_descriptor) #3 {
  ^
  
  Input file: 
  Check file: 
C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp
  
  -dump-input=help explains the following input dump.
  
  Input was:
  <<
  1: ; ModuleID = 
'C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp'
 
  label:50'0 
X
 error: no match found
  2: source_filename = 
"C:\\ws\\w32-1\\llvm-project\\premerge-checks\\clang\\test\\CodeGenCXX\\cxx1z-constexpr-if.cpp"
 
  label:50'0 
~~
  3: target datalayout = 
"e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" 
  label:50'0 
~
  4: target triple = "x86_64-pc-windows-msvc" 
  label:50'0 ~
  5:  
  label:50'0 ~
  6: %"struct.BlockThisCapture::S" = type { i8 } 
  label:50'0 
  .
  .
  .
 48:  call void %0(ptr noundef @__block_literal_global) 
  label:50'0 ~~~
 49:  ret void 
  label:50'0 ~~
 50: } 
  label:50'0 ~~
 51:  
  label:50'0 ~
 52: ; Function Attrs: noinline nounwind optnone 
  label:50'0 
 53: define internal void 
@"__??$m@$0A@@S@BlockThisCapture@@QEAAXXZ_block_invoke"(ptr noundef 
%.block_descriptor) #3 { 
  label:50'0 
~~
  label:50'1 ?  
possible intended match
 54: entry: 
  label:50'0 ~~~
 55:  %.block_descriptor.addr = alloca ptr, align 8 
  label:50'0 ~~~
 56:  %block.addr = alloca ptr, align 8 
  label:50'0 ~~~
 57:  store ptr %.block_descriptor, ptr %.block_descriptor.addr, 
align 8 
  label:50'0 

 58:  store ptr %.block_descriptor, ptr %block.addr, align 8 
  label:50'0 
  .
  .
  .
  >>
  
  error: command failed with exit status: 1

It looks like you may need a target triple to ensure the mangled names are 
consistent.

Also, can you add a release note for the fix?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE

[PATCH] D143210: [PowerPC] Include vector bool and pixel when emitting lax warning

2023-02-15 Thread Maryam Moghadas via Phabricator via cfe-commits
maryammo added inline comments.



Comment at: clang/lib/Sema/SemaExpr.cpp:9845
 if (anyAltivecTypes(RHSType, LHSType) &&
-!areSameVectorElemTypes(RHSType, LHSType))
+!Context.areCompatibleVectorTypes(RHSType, LHSType))
   Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)

amyk wrote:
> Might be a silly question, but what does it mean to be a "compatible" vector 
> type?
`areCompatibleVectorTypes` is defined in lib/AST/ASTContext.cpp,  it considers 
all vectors with the same unqualified types to be compatible, also vectors with 
the same number of elements where neither of them is vector bool/pixel or some 
specific SVE types are compatible.  


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143210

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


[PATCH] D144058: [clang][deps] Split lookupModuleOutput out of DependencyConsumer NFC

2023-02-15 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 accepted this revision.
jansvoboda11 added inline comments.
This revision is now accepted and ready to land.



Comment at: 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h:64-66
+/// Dependency scanner callbacks that are used during scanning to influence the
+/// behaviour of the scan - for example, to customize the scanned invocations.
+class DependencyActions {

benlangmuir wrote:
> jansvoboda11 wrote:
> > What do the downstream callbacks do? The class name sounds a bit generic 
> > for something you can call `lookupModuleOutput()` on, but maybe that's the 
> > right name with more context. It's also very similar to the existing 
> > `DependencyScanningAction`.
> They are callbacks that modify the ScanInstance itself, or one of the 
> CompilerInvocations being constructed (either for the TU or for module 
> dependencies).  In practice, we use this to add caching support - modifying 
> invocations to use inputs from a CAS. I chose "actions" based on the fact 
> they are acting on the scanner/invocations, rather than simply consuming the 
> information.  While lookupModuleOutput does not directly modify the 
> invcation, it does indirectly via the ModuleDepCollector incorporating its 
> results into the invocation.  If you're interested, here are our downstream 
> callbacks that I would move into this interface: 
> https://github.com/apple/llvm-project/blob/next/clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h#L49
> 
> RE: DependencyScanningAction: I agree it's not ideal that these names are 
> "close".  On the other hand, they're not too likely to be confused in 
> practice since they have very different roles -- the DependencyScanningAction 
> is not exposed to clients, and it's a tooling action not something you use to 
> control the scan.  We also have other "actions" like the FrontendAction we 
> create, which again have a different role.
> 
> Happy to consider suggestions for a better name!
Thanks, that's helpful. My preference would be slightly towards something more 
specific-sounding, maybe `ScanningAdjuster`, `ScannerAndDependencyAdjuster`, 
but LGTM as-is too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144058

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


[PATCH] D144037: [clang-tidy] allow tests to use --config-file instead of --config

2023-02-15 Thread Alexis Murzeau via Phabricator via cfe-commits
amurzeau updated this revision to Diff 497773.
amurzeau retitled this revision from "[clang-tidy] allow tests to use 
-config-file instead of -config" to "[clang-tidy] allow tests to use 
--config-file instead of --config".
amurzeau added a comment.

Allow use of --config and --config-file (with double dashes)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144037

Files:
  clang-tools-extra/test/clang-tidy/check_clang_tidy.py
  
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation-cfgfile.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation.cpp
@@ -1,5 +1,4 @@
-// RUN: clang-tidy %s 
--config-file=%S/Inputs/identifier-naming/hungarian-notation2/.clang-tidy 2>&1 \
-// RUN:   | FileCheck -check-prefixes=CHECK-MESSAGES %s
+// RUN: %check_clang_tidy %s readability-identifier-naming %t -- 
--config-file=%S/Inputs/identifier-naming/hungarian-notation1/.clang-tidy
 
 // clang-format off
 typedef signed char int8_t; // NOLINT
Index: 
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation-cfgfile.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation-cfgfile.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation-cfgfile.cpp
@@ -1,5 +1,4 @@
-// RUN: clang-tidy %s 
--config-file=%S/Inputs/identifier-naming/hungarian-notation1/.clang-tidy 2>&1 \
-// RUN:   | FileCheck -check-prefixes=CHECK-MESSAGES %s
+// RUN: %check_clang_tidy %s readability-identifier-naming %t -- 
--config-file=%S/Inputs/identifier-naming/hungarian-notation2/.clang-tidy
 
 // clang-format off
 typedef signed char int8_t; // NOLINT
Index: clang-tools-extra/test/clang-tidy/check_clang_tidy.py
===
--- clang-tools-extra/test/clang-tidy/check_clang_tidy.py
+++ clang-tools-extra/test/clang-tidy/check_clang_tidy.py
@@ -107,9 +107,10 @@
 # If the test does not specify a config style, force an empty one; 
otherwise
 # auto-detection logic can discover a ".clang-tidy" file that is not 
related to
 # the test.
-if not any(
-[arg.startswith('-config=') for arg in self.clang_tidy_extra_args]):
-  self.clang_tidy_extra_args.append('-config={}')
+if not any([
+re.match('^-?-config(-file)?=', arg)
+for arg in self.clang_tidy_extra_args]):
+  self.clang_tidy_extra_args.append('--config={}')
 
 if extension in ['.m', '.mm']:
   self.clang_extra_args = ['-fobjc-abi-version=2', '-fobjc-arc', 
'-fblocks'] + \


Index: clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation.cpp
@@ -1,5 +1,4 @@
-// RUN: clang-tidy %s --config-file=%S/Inputs/identifier-naming/hungarian-notation2/.clang-tidy 2>&1 \
-// RUN:   | FileCheck -check-prefixes=CHECK-MESSAGES %s
+// RUN: %check_clang_tidy %s readability-identifier-naming %t -- --config-file=%S/Inputs/identifier-naming/hungarian-notation1/.clang-tidy
 
 // clang-format off
 typedef signed char int8_t; // NOLINT
Index: clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation-cfgfile.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation-cfgfile.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation-cfgfile.cpp
@@ -1,5 +1,4 @@
-// RUN: clang-tidy %s --config-file=%S/Inputs/identifier-naming/hungarian-notation1/.clang-tidy 2>&1 \
-// RUN:   | FileCheck -check-prefixes=CHECK-MESSAGES %s
+// RUN: %check_clang_tidy %s readability-identifier-naming %t -- --config-file=%S/Inputs/identifier-naming/hungarian-notation2/.clang-tidy
 
 // clang-format off
 typedef signed char int8_t; // NOLINT
Index: clang-tools-extra/test/clang-tidy/check_clang_tidy.py
===
--- clang-tools-extra/test/clang-tidy/check_clang_tidy.py
+++ clang-tools-extra/test/clang-tidy/check_clang_tidy.py
@@ -107,9 +107,10 @@
   

[clang] 8c1f77a - [clang-format] Fix windows build.

2023-02-15 Thread Manuel Klimek via cfe-commits

Author: Manuel Klimek
Date: 2023-02-15T20:59:43Z
New Revision: 8c1f77af7fd14d5a611246aa16b9693d3ebcee22

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

LOG: [clang-format] Fix windows build.

MSVC needs a return after llvm_unreachable.

Added: 


Modified: 
clang/lib/Format/FormatTokenSource.h

Removed: 




diff  --git a/clang/lib/Format/FormatTokenSource.h 
b/clang/lib/Format/FormatTokenSource.h
index 0be46287f6b74..d93efaf676087 100644
--- a/clang/lib/Format/FormatTokenSource.h
+++ b/clang/lib/Format/FormatTokenSource.h
@@ -18,6 +18,7 @@
 #include "FormatToken.h"
 #include "UnwrappedLineParser.h"
 #include "llvm/ADT/DenseMap.h"
+#include 
 
 #define DEBUG_TYPE "format-token-source"
 
@@ -237,6 +238,7 @@ class ScopedMacroState : public FormatTokenSource {
 
   FormatToken *insertTokens(ArrayRef Tokens) override {
 llvm_unreachable("Cannot insert tokens while parsing a macro.");
+return nullptr;
   }
 
 private:



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


[PATCH] D144016: [Sema] Relax a failing assertion in TransformBlockExpr

2023-02-15 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak updated this revision to Diff 497776.
ahatanak added a comment.

Add triple to the test and add release note for the fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144016

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/TreeTransform.h
  clang/test/CodeGenCXX/cxx1z-constexpr-if.cpp


Index: clang/test/CodeGenCXX/cxx1z-constexpr-if.cpp
===
--- clang/test/CodeGenCXX/cxx1z-constexpr-if.cpp
+++ clang/test/CodeGenCXX/cxx1z-constexpr-if.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++1z %s -emit-llvm -o - | FileCheck %s 
--implicit-check-not=should_not_be_used
+// RUN: %clang_cc1 -std=c++1z %s -emit-llvm -fblocks -triple 
x86_64-apple-darwin10 -o - | FileCheck %s 
--implicit-check-not=should_not_be_used
 
 void should_be_used_1();
 void should_be_used_2();
@@ -32,3 +32,20 @@
 // CHECK: should_be_used_1
 // CHECK: should_be_used_2
 // CHECK: should_be_used_3
+
+namespace BlockThisCapture {
+  void foo();
+  struct S {
+template 
+void m() {
+  ^{ if constexpr(b) (void)this; else foo();  }();
+}
+  };
+
+  void test() {
+S().m();
+  }
+}
+
+// CHECK-LABEL: define internal void 
@___ZN16BlockThisCapture1S1mILb0EEEvv_block_invoke(
+// CHECK: call void @_ZN16BlockThisCapture3fooEv(
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -14598,7 +14598,12 @@
  oldCapture));
   assert(blockScope->CaptureMap.count(newCapture));
 }
-assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
+
+// The this pointer may not be captured by the instantiated block, even 
when
+// it's captured by the original block, if the expression causing the
+// capture is in the discarded branch of a constexpr if statement.
+assert((!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) &&
+   "this pointer isn't captured in the old block");
   }
 #endif
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -67,6 +67,9 @@
 - Fix crash when evaluating consteval constructor of derived class whose base
   has more than one field. This fixes
   `Issue 60166 `_.
+- Fix assert that fails when the expression causing the this pointer to be
+  captured by a block is part of a constexpr if statement's branch and
+  instantiation of the enclosing method causes the branch to be discarded.
 
 Improvements to Clang's diagnostics
 ^^^


Index: clang/test/CodeGenCXX/cxx1z-constexpr-if.cpp
===
--- clang/test/CodeGenCXX/cxx1z-constexpr-if.cpp
+++ clang/test/CodeGenCXX/cxx1z-constexpr-if.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++1z %s -emit-llvm -o - | FileCheck %s --implicit-check-not=should_not_be_used
+// RUN: %clang_cc1 -std=c++1z %s -emit-llvm -fblocks -triple x86_64-apple-darwin10 -o - | FileCheck %s --implicit-check-not=should_not_be_used
 
 void should_be_used_1();
 void should_be_used_2();
@@ -32,3 +32,20 @@
 // CHECK: should_be_used_1
 // CHECK: should_be_used_2
 // CHECK: should_be_used_3
+
+namespace BlockThisCapture {
+  void foo();
+  struct S {
+template 
+void m() {
+  ^{ if constexpr(b) (void)this; else foo();  }();
+}
+  };
+
+  void test() {
+S().m();
+  }
+}
+
+// CHECK-LABEL: define internal void @___ZN16BlockThisCapture1S1mILb0EEEvv_block_invoke(
+// CHECK: call void @_ZN16BlockThisCapture3fooEv(
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -14598,7 +14598,12 @@
  oldCapture));
   assert(blockScope->CaptureMap.count(newCapture));
 }
-assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
+
+// The this pointer may not be captured by the instantiated block, even when
+// it's captured by the original block, if the expression causing the
+// capture is in the discarded branch of a constexpr if statement.
+assert((!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) &&
+   "this pointer isn't captured in the old block");
   }
 #endif
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -67,6 +67,9 @@
 - Fix crash when evaluating consteval constructor of derived class whose base
   has more than one field. This fixes
   `Issue 60166 

[PATCH] D143109: [Sema] Push a LambdaScopeInfo before calling SubstDefaultArgument

2023-02-15 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann requested changes to this revision.
tahonermann added inline comments.
This revision now requires changes to proceed.



Comment at: clang/lib/Sema/SemaExpr.cpp:19085-19092
+  // If the variable is used in a default argument expression of a lambda call
+  // operator, switch to the enclosing context to sync up with the function
+  // scope.
+  if (isLambdaCallOperator(DC))
+if (auto *PVD = dyn_cast_or_null(
+ExprEvalContexts.back().ManglingContextDecl))
+  if (PVD->getDeclContext() == DC)

I'm struggling to understand the change. If I'm following correctly, it looks 
like we're trying to capture the variable used in the default argument. If so, 
that seems wrong; I think we shouldn't even be trying to capture a variable for 
such usage.

I jumped into a debugger to poke around a bit. Perhaps the right change is to 
detect the use in a default argument in the code below so that the call to 
`getCapturedDeclRefType()` can be skipped for a non-ODR use.
  /localdisk2/thonerma/llvm-project/clang/lib/Sema/SemaExpr.cpp:
   3265 ExprResult Sema::BuildDeclarationNameExpr(
   3266 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 
NamedDecl *D,
   3267 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
   3268 bool AcceptInvalidDecl) {
  .
   3326   switch (D->getKind()) {
  .
   3389   case Decl::Var:
   3390   case Decl::VarTemplateSpecialization:
   3391   case Decl::VarTemplatePartialSpecialization:
   3392   case Decl::Decomposition:
   3393   case Decl::OMPCapturedExpr:
   3394 // In C, "extern void blah;" is valid and is an r-value.
   3395 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
   3396 type->isVoidType()) {
   3397   valueKind = VK_PRValue;
   3398   break;
   3399 }
   3400 [[fallthrough]];
   3401
   3402   case Decl::ImplicitParam:
   3403   case Decl::ParmVar: {
   3404 // These are always l-values.
   3405 valueKind = VK_LValue;
   3406 type = type.getNonReferenceType();
   3407
   3408 // FIXME: Does the addition of const really only apply in
   3409 // potentially-evaluated contexts? Since the variable isn't actually
   3410 // captured in an unevaluated context, it seems that the answer is 
no.
   3411 if (!isUnevaluatedContext()) {
   3412   QualType CapturedType = getCapturedDeclRefType(cast(VD), 
Loc);
   3413   if (!CapturedType.isNull())
   3414 type = CapturedType;
   3415 }
   3416
   3417 break;
   3418   }
  .
   3516 }



Comment at: clang/test/SemaCXX/lambda-default-arg.cpp:6
+  return [=](float b = a) -> bool {
+return a < 0;
+  }();

Is the use of `a` in the lambda body intentional? It isn't needed to reproduce 
the assertion failure, so its presence here is a bit confusing from a test 
perspective as it implies that variable capture is somehow related. I suggest 
just returning `true`. Likewise for the other two tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143109

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


[PATCH] D143919: [Clang] Copy strictfp attribute from pattern to instantiation

2023-02-15 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

If the "strictfp" attribute is based on the contents of the function body, 
should we recompute it when the function is instantiated, as opposed to copying 
it?  For example, say you have a pragma inside an "if constexpr"; should that 
set the strictfp attribute if it's discarded?

Otherwise, I guess updateAttrsForLateParsedTemplate makes sense.




Comment at: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp:824
+  continue;
+}
+

Is this necessary?  The non-delayed-parsed case seems to work correctly on 
trunk without any changes, so I suspect the autogenerated 
sema::instantiateTemplateAttribute is doing the right thing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143919

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


[clang] f5aa8d1 - [Clang][docs] Update the release notes page to the new skeleton

2023-02-15 Thread Roy Jacobson via cfe-commits

Author: Roy Jacobson
Date: 2023-02-15T23:53:38+02:00
New Revision: f5aa8d191a5b5ea118281bfa410bdb2ee961c704

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

LOG: [Clang][docs] Update the release notes page to the new skeleton

Was discussed at https://reviews.llvm.org/D142578.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ab7518cc2dc6..abb6f0ae8e92 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -13,7 +13,7 @@ Written by the `LLVM Team `_
   .. warning::
  These are in-progress notes for the upcoming Clang |version| release.
  Release notes for previous releases can be found on
- `the Download Page `_.
+ `the Releases Page `_.
 
 Introduction
 
@@ -23,25 +23,30 @@ frontend, part of the LLVM Compiler Infrastructure, release 
|release|. Here we
 describe the status of Clang in some detail, including major
 improvements from the previous release and new feature work. For the
 general LLVM release notes, see `the LLVM
-documentation `_. All LLVM
-releases may be downloaded from the `LLVM releases web
-site `_.
+documentation `_. For the libc++ 
release notes,
+see `this page `_. All LLVM releases
+may be downloaded from the `LLVM releases web site 
`_.
 
 For more information about Clang or LLVM, including information about the
 latest release, please see the `Clang Web Site `_ or 
the
 `LLVM Web Site `_.
 
-Note that if you are reading this file from a Git checkout or the
-main Clang web page, this document applies to the *next* release, not
-the current one. To see the release notes for a specific release, please
-see the `releases page `_.
-
 Potentially Breaking Changes
 
 These changes are ones which we think may surprise users when upgrading to
 Clang |release| because of the opportunity they pose for disruption to existing
 code bases.
 
+
+C/C++ Language Potentially Breaking Changes
+---
+
+C++ Specific Potentially Breaking Changes
+-
+
+ABI Changes in This Version
+---
+
 What's New in Clang |release|?
 ==
 Some of the major new features and improvements to Clang are listed
@@ -49,33 +54,28 @@ here. Generic improvements to Clang as a whole or to its 
underlying
 infrastructure are described first, followed by language-specific
 sections with improvements to Clang's support for those languages.
 
-Major New Features
---
+C++ Language Changes
+
+- Improved ``-O0`` code generation for calls to ``std::forward_like``. 
Similarly to
+  ``std::move, std::forward`` et al. it is now treated as a compiler builtin 
and implemented
+  directly rather than instantiating the definition from the standard library.
 
-Bug Fixes
--
-- Fix crash on invalid code when looking up a destructor in a templated class
-  inside a namespace. This fixes
-  `Issue 59446 `_.
-- Fix crash when diagnosing incorrect usage of ``_Nullable`` involving alias
-  templates. This fixes
-  `Issue 60344 `_.
-- Fix confusing warning message when ``/clang:-x`` is passed in ``clang-cl``
-  driver mode and emit an error which suggests using ``/TC`` or ``/TP``
-  ``clang-cl`` options instead. This fixes
-  `Issue 59307 `_.
-- Fix crash when evaluating consteval constructor of derived class whose base
-  has more than one field. This fixes
-  `Issue 60166 `_.
+C++20 Feature Support
+^
 
-Improvements to Clang's diagnostics
-^^^
-- We now generate a diagnostic for signed integer overflow due to unary minus
-  in a non-constant expression context. This fixes
-  `Issue 31643 `_
-- Clang now warns by default for C++20 and later about deprecated capture of
-  ``this`` with a capture default of ``=``. This warning can be disabled with
-  ``-Wno-deprecated-this-capture``.
+C++2b Feature Support
+^
+
+Resolutions to C++ Defect Reports
+^
+
+C Language Changes
+--
+
+C2x Featur

[PATCH] D144136: Add a "remark" to report on array accesses

2023-02-15 Thread Bill Wendling via Phabricator via cfe-commits
void created this revision.
Herald added a project: All.
void requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This will report a ton of information. It's basically only good for
piping to a file and using Perl to gather any useful information.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144136

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaChecking.cpp


Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -16323,6 +16323,10 @@
 else if (size.getBitWidth() < index.getBitWidth())
   size = size.zext(index.getBitWidth());
 
+Context.getDiagnostics().Report(
+BaseExpr->getBeginLoc(), diag::remark_array_access)
+<< 0 << ArrayTy->desugar() << toString(index, 10, true);
+
 // For array subscripting the index must be less than size, but for pointer
 // arithmetic also allow the index (offset) to be equal to size since
 // computing the next address after the end of the array is legal and
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9450,6 +9450,10 @@
 def note_array_declared_here : Note<
   "array %0 declared here">;
 
+def remark_array_access : Remark<
+  "accessing %select{fixed|dynamic}0 sized array %1 by %2">,
+  InGroup;
+
 def warn_inconsistent_array_form : Warning<
   "argument %0 of type %1 with mismatched bound">,
   InGroup, DefaultIgnore;
Index: clang/include/clang/Basic/DiagnosticGroups.td
===
--- clang/include/clang/Basic/DiagnosticGroups.td
+++ clang/include/clang/Basic/DiagnosticGroups.td
@@ -1304,6 +1304,9 @@
 def ProfileInstrUnprofiled : DiagGroup<"profile-instr-unprofiled">;
 def MisExpect : DiagGroup<"misexpect">;
 
+// Array bounds remarks.
+def ArrayBoundsRemarks : DiagGroup<"array-bounds">;
+
 // AddressSanitizer frontend instrumentation remarks.
 def SanitizeAddressRemarks : DiagGroup<"sanitize-address">;
 


Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -16323,6 +16323,10 @@
 else if (size.getBitWidth() < index.getBitWidth())
   size = size.zext(index.getBitWidth());
 
+Context.getDiagnostics().Report(
+BaseExpr->getBeginLoc(), diag::remark_array_access)
+<< 0 << ArrayTy->desugar() << toString(index, 10, true);
+
 // For array subscripting the index must be less than size, but for pointer
 // arithmetic also allow the index (offset) to be equal to size since
 // computing the next address after the end of the array is legal and
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9450,6 +9450,10 @@
 def note_array_declared_here : Note<
   "array %0 declared here">;
 
+def remark_array_access : Remark<
+  "accessing %select{fixed|dynamic}0 sized array %1 by %2">,
+  InGroup;
+
 def warn_inconsistent_array_form : Warning<
   "argument %0 of type %1 with mismatched bound">,
   InGroup, DefaultIgnore;
Index: clang/include/clang/Basic/DiagnosticGroups.td
===
--- clang/include/clang/Basic/DiagnosticGroups.td
+++ clang/include/clang/Basic/DiagnosticGroups.td
@@ -1304,6 +1304,9 @@
 def ProfileInstrUnprofiled : DiagGroup<"profile-instr-unprofiled">;
 def MisExpect : DiagGroup<"misexpect">;
 
+// Array bounds remarks.
+def ArrayBoundsRemarks : DiagGroup<"array-bounds">;
+
 // AddressSanitizer frontend instrumentation remarks.
 def SanitizeAddressRemarks : DiagGroup<"sanitize-address">;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D143849: [Clang][OpenCL] Allow pointers in structs as kernel arguments from 2.0

2023-02-15 Thread Ayal Zaks via Phabricator via cfe-commits
Ayal added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:9494
+  // of SVM.
+  if (S.getLangOpts().getOpenCLCompatibleVersion() > 120 &&
+  (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam))

Anastasia wrote:
> Anastasia wrote:
> > Ayal wrote:
> > > Anastasia wrote:
> > > > I think it should be possible to merge this with `if` below to avoid 
> > > > condition duplication.
> > > > 
> > > > 
> > > Sure, but that trades one duplication for another, rather than clearly 
> > > separating the early-continue case early?
> > > 
> > > ```
> > >   if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
> > > if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
> > >   continue;
> > > S.Diag(Param->getLocation(),
> > >diag::err_record_with_pointers_kernel_param)
> > >   << PT->isUnionType()
> > >   << PT;
> > >   } else if (ParamType == InvalidAddrSpacePtrKernelParam) {
> > > S.Diag(Param->getLocation(),
> > >diag::err_record_with_pointers_kernel_param)
> > >   << PT->isUnionType()
> > >   << PT;
> > >   } else {
> > > S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << 
> > > PT;
> > > 
> > > ```
> > I am mainly thinking in terms of maintenance if for example someone fixes 
> > one if and forgets another. Or if ifs will get separated by some other code 
> > and then it is not easy to see that the same thing is handled differently 
> > in OpenCL versions. 
> > 
> > Unfortunately we have a lot of those cases, I know this function has early 
> > exists but it is not a common style.
> > 
> > 
> > I was talking about something like:
> > 
> > 
> > ```
> > if (((S.getLangOpts().getOpenCLCompatibleVersion() <= 120) &&
> > (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam)) ||
> >   ParamType == InvalidAddrSpacePtrKernelParam)
> > ```
> > 
> > It would also be ok to separate `InvalidAddrSpacePtrKernelParam` since it's 
> > handling different feature.
> Sorry I have forgotten that this part of the code is expected to handle the 
> diagnostics only. The decision that the kernel parameter is wrong is done in 
> `getOpenCLKernelParameterType`. I think you should alter the conditions there 
> to check for OpenCL version and avoid classifying cases you care about as 
> `PtrKernelParam` or `PtrPtrKernelParam`. Then here you wouldn't need this 
> extra if/continue block. 
Hmm, would that be better? This part of the code, namely 
`checkIsValidOpenCLKernelParameter()`, does check the validity of arguments 
classified by `getOpenCLKernelParameterType()` in addition to handling 
diagnostics. E.g., the first case above decides that arguments of 
pointer-to-pointer type are wrong along with proper diagnostics for OpenCL 1.x 
while allowing them for other OpenCL versions.

Struct arguments are simply classified as records by 
getOpenCLKernelParameterType(), whereas this part of the code traverses each 
struct and calls getOpenCLKernelParameterType() on each field - the latter 
seems  unaware if it was invoked on a struct field or not? If it is (made) 
aware, it could indeed return a (new kind of?) invalid type instead of pointer 
type for OpenCL 1.x - how would the right err_record_with_pointers_kernel_param 
diagnostics then be handled? If desired, such refactoring should probably be 
done independent of this fix?


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

https://reviews.llvm.org/D143849

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


[clang] a851d46 - [Clang][Driver] Fix integer normalization with KCFI

2023-02-15 Thread Sami Tolvanen via cfe-commits

Author: Sami Tolvanen
Date: 2023-02-16T00:21:31Z
New Revision: a851d46e07c1234a0763b4630c8475c73208e776

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

LOG: [Clang][Driver] Fix integer normalization with KCFI

Commit 71c7313f42d2b6063fea09854cf4fc46fd0627e1 added integer
normalization for CFI, but doesn't correctly pass the argument
with -fsanitize=kcfi. Set CfiICallNormalizeIntegers also with
SanitizerKind::KCFI to fix the issue.

Added: 


Modified: 
clang/lib/Driver/SanitizerArgs.cpp

Removed: 




diff  --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index 7f7ad238c89f4..390faef0dbdf1 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -726,8 +726,11 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
  options::OPT_fno_sanitize_cfi_canonical_jump_tables, 
true);
   }
 
-  if (AllAddedKinds & SanitizerKind::KCFI && DiagnoseErrors) {
-if (AllAddedKinds & SanitizerKind::CFI)
+  if (AllAddedKinds & SanitizerKind::KCFI) {
+CfiICallNormalizeIntegers =
+Args.hasArg(options::OPT_fsanitize_cfi_icall_normalize_integers);
+
+if (AllAddedKinds & SanitizerKind::CFI && DiagnoseErrors)
   D.Diag(diag::err_drv_argument_not_allowed_with)
   << "-fsanitize=kcfi"
   << lastArgumentForMask(D, Args, SanitizerKind::CFI);



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


[PATCH] D142867: [Clang] Add machinery to catch overflow in unary minus outside of a constant expression context

2023-02-15 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added a comment.

In D142867#4108079 , @eaeltsin wrote:

> The warning now fires even if overflow is prevented with `if constexpr`:
>
>   if constexpr (width <= 64) {
> if constexpr (width == 64) {
>   return 1;
> }
> return -static_cast(uint64_t{1} << (width - 1));
>   }
>
> https://godbolt.org/z/M3xdcKd3M

For reference, actually placing the second return into an `else` block (thus 
making it a discarded statement) does suppress the diagnostic:
https://godbolt.org/z/Kb6Md5PrK

I also question the focus on `if constexpr`. Replacing with `if (true) { return 
1; }` should be as effective in the non-`else`-block case in suppressing the 
warning in terms of QoI.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142867

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


[PATCH] D144147: [Clang][RISCV] Sort test cases into its mnemonics

2023-02-15 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD created this revision.
eopXD added reviewers: craig.topper, kito-cheng.
Herald added subscribers: luke, VincentWu, vkmr, frasercrmck, evandro, 
luismarques, apazos, sameer.abuasal, s.egerton, Jim, benna, psnobl, jocewei, 
PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, edward-jones, zzheng, jrtc27, 
shiva0217, niosHD, sabuasal, simoncook, johnrusso, rbar, asb, arichardson.
Herald added a project: All.
eopXD requested review of this revision.
Herald added subscribers: cfe-commits, pcwang-thead, MaskRay.
Herald added a project: clang.

Referencing the corresponding change from the source of the test cases:
riscv-non-isa/rvv-intrinsic-doc#196


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144147

Files:
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfncvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfncvt_rod.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfncvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vlmul.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vlmul_ext_v.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vlmul_trunc_v.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vsext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vsext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vsext_vf4.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vsext_vf8.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vzext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vzext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vzext_vf4.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vzext_vf8.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfncvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfncvt_rod.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfncvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfwcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfwcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vlmul.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vlmul_ext_v.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vlmul_trunc_v.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vsext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vsext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vsext_vf4.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vsext_vf8.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vzext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vzext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vzext_vf4.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vzext_vf8.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfncvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfncvt_rod.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfncvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfwcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfwcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vsext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vsext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vsext_vf4.c
  
clang/test/CodeGen/RISCV/rvv-intrinsi

[PATCH] D139741: [clang][CodeGen] Use base subobject type layout for potentially-overlapping fields

2023-02-15 Thread Vladislav Dzhidzhoev via Phabricator via cfe-commits
dzhidzhoev updated this revision to Diff 497847.
dzhidzhoev added a comment.

Simplified condition in lowerUnion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139741

Files:
  clang/include/clang/AST/Decl.h
  clang/lib/AST/Decl.cpp
  clang/lib/AST/RecordLayoutBuilder.cpp
  clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
  clang/test/CodeGenCXX/no-unique-address-3.cpp

Index: clang/test/CodeGenCXX/no-unique-address-3.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/no-unique-address-3.cpp
@@ -0,0 +1,209 @@
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -emit-llvm -fdump-record-layouts -std=c++17 %s -o %t | FileCheck %s
+
+// CHECK-LABEL:  0 | class Empty (empty)
+// CHECK-NEXT: | [sizeof=1, dsize=1, align=1,
+// CHECK-NEXT: |  nvsize=1, nvalign=1]
+// CHECK-LABEL:  0 | class Second
+// CHECK-NEXT:   0 |   class Empty (base) (empty)
+// CHECK-NEXT:   0:0-0 |   short A
+// CHECK-NEXT: | [sizeof=2, dsize=1, align=2,
+// CHECK-NEXT: |  nvsize=1, nvalign=2]
+// CHECK-LABEL:  0 | class Foo
+// CHECK-NEXT:   0 |   class Empty (base) (empty)
+// CHECK-NEXT:   2 |   class Second NZNoUnique
+// CHECK-NEXT:   2 | class Empty (base) (empty)
+// CHECK-NEXT:   2:0-0 | short A
+// CHECK-NEXT:   3 |   char B
+// CHECK-NEXT: | [sizeof=4, dsize=4, align=2,
+// CHECK-NEXT: |  nvsize=4, nvalign=2]
+
+class Empty {};
+
+// CHECK-LABEL: LLVMType:%class.Second = type { i8, i8 }
+// CHECK-NEXT:  NonVirtualBaseLLVMType:%class.Second.base = type { i8 }
+class Second : Empty {
+  short A : 1;
+};
+
+// CHECK-LABEL:   LLVMType:%class.Foo = type { [2 x i8], %class.Second.base, i8 }
+// CHECK-NEXT:NonVirtualBaseLLVMType:%class.Foo = type { [2 x i8], %class.Second.base, i8 }
+class Foo : Empty {
+  [[no_unique_address]] Second NZNoUnique;
+  char B;
+};
+Foo I;
+
+// CHECK-LABEL:  0 | class SecondEmpty (empty)
+// CHECK-NEXT:   0 |   class Empty (base) (empty)
+// CHECK-NEXT: | [sizeof=1, dsize=0, align=1,
+// CHECK-NEXT: |  nvsize=1, nvalign=1]
+class SecondEmpty: Empty {
+};
+
+// CHECK-LABEL:  0 | class Bar
+// CHECK-NEXT:   0 |   class Empty (base) (empty)
+// CHECK-NEXT:   1 |   class SecondEmpty ZNoUnique (empty)
+// CHECK-NEXT:   1 | class Empty (base) (empty)
+// CHECK-NEXT:   0 |   char C
+// CHECK-NEXT: | [sizeof=2, dsize=1, align=1,
+// CHECK-NEXT: |  nvsize=2, nvalign=1]
+
+// CHECK-LABEL:  LLVMType:%class.Bar = type { i8, i8 }
+// CHECK-NEXT:   NonVirtualBaseLLVMType:%class.Bar = type { i8, i8 }
+class Bar : Empty {
+  [[no_unique_address]] SecondEmpty ZNoUnique;
+  char C;
+};
+Bar J;
+
+// CHECK-LABEL:  0 | class IntFieldClass
+// CHECK-NEXT:   0 |   class Empty (base) (empty)
+// CHECK-NEXT:   2 |   class Second Field
+// CHECK-NEXT:   2 | class Empty (base) (empty)
+// CHECK-NEXT:   2:0-0 | short A
+// CHECK-NEXT:   4 |   int C
+// CHECK-NEXT: | [sizeof=8, dsize=8, align=4,
+// CHECK-NEXT: |  nvsize=8, nvalign=4]
+
+// CHECK-LABEL:   LLVMType:%class.IntFieldClass = type { [2 x i8], %class.Second.base, i32 }
+// CHECK-NEXT:NonVirtualBaseLLVMType:%class.IntFieldClass = type { [2 x i8], %class.Second.base, i32 }
+class IntFieldClass : Empty {
+  [[no_unique_address]] Second Field;
+  int C;
+};
+IntFieldClass K;
+
+// CHECK-LABEL: 0 | class UnionClass
+// CHECK-NEXT:  0 |   class Empty (base) (empty)
+// CHECK-NEXT:  0 |   union UnionClass
+// CHECK-NEXT:  0 | int I
+// CHECK-NEXT:  0 | char C
+// CHECK-NEXT:  4 |   int C
+// CHECK-NEXT:| [sizeof=8, dsize=8, align=4,
+// CHECK-NEXT:|  nvsize=8, nvalign=4]
+
+// CHECK-LABEL:  LLVMType:%class.UnionClass = type { %union.anon, i32 }
+// CHECK-NEXT:   NonVirtualBaseLLVMType:%class.UnionClass = type { %union.anon, i32 }
+// CHECK-NEXT:   IsZeroInitializable:1
+// CHECK-NEXT:   BitFields:[
+// CHECK-NEXT: ]>
+class UnionClass : Empty {
+  [[no_unique_address]] union {
+int I;
+char C;
+  } U;
+  int C;
+};
+UnionClass L;
+
+// CHECK-LABEL: 0 | class EnumClass
+// CHECK-NEXT:  0 |   class Empty (base) (empty)
+// CHECK-NEXT:  0 |   enum E A
+// CHECK-NEXT:  4 |   int C
+// CHECK-NEXT:| [sizeof=8, dsize=8, align=4,
+// CHECK-NEXT:|  nvsize=8, nvalign=4]
+
+// CHECK-LABEL:  LLVMType:%class.EnumClass = type { i32, i32 }
+// CHECK-NEXT:   NonVirtualBaseLLVMType:%class.EnumClass = type { i32, i32 }
+// CHECK-NEXT:   IsZeroInitializable:1
+// CHECK-NEXT:   BitFields:[
+// CHECK-NEXT: ]>
+class EnumClass : Empty {
+  [[no_unique_address]] enum class E { X, Y

[PATCH] D144149: [Serialization] Don't warn when a deserialized category is equivalent to an existing one.

2023-02-15 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai created this revision.
vsapsai added reviewers: ChuanqiXu, jansvoboda11.
Herald added a subscriber: ributzka.
Herald added a project: All.
vsapsai requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

A single class allows multiple categories to be defined for it. But if
two of such categories have the same name, we emit a warning. It's not a
hard error but a good indication of a potential mistake.

With modules, we can end up with the same category in different modules.
Diagnosing such a situation has little value as the categories in
different modules are equivalent and don't reflect the usage of the same
name for different purposes. When we deserialize a duplicate category,
compare it to an existing one and warn only when the new one is
different.

rdar://104582081


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144149

Files:
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/test/Modules/compare-objc-interface.m
  clang/test/Modules/hidden-duplicates.m
  clang/test/Modules/objc-categories.m

Index: clang/test/Modules/objc-categories.m
===
--- clang/test/Modules/objc-categories.m
+++ clang/test/Modules/objc-categories.m
@@ -8,8 +8,6 @@
 
 @import category_bottom;
 
-// expected-note@Inputs/category_left.h:14 {{previous definition}}
-// expected-warning@Inputs/category_right.h:12 {{duplicate definition of category}}
 // expected-note@Inputs/category_top.h:1 {{receiver is instance of class declared here}}
 
 @interface Foo(Source)
Index: clang/test/Modules/hidden-duplicates.m
===
--- clang/test/Modules/hidden-duplicates.m
+++ clang/test/Modules/hidden-duplicates.m
@@ -32,6 +32,7 @@
 
 @interface NSObject @end
 @class ForwardDeclaredInterfaceWithoutDefinition;
+@interface NSObject(CategoryForTesting) @end
 
 NSObject *interfaceDefinition(NSObject *o);
 NSObject *forwardDeclaredInterface(NSObject *o);
Index: clang/test/Modules/compare-objc-interface.m
===
--- clang/test/Modules/compare-objc-interface.m
+++ clang/test/Modules/compare-objc-interface.m
@@ -444,3 +444,54 @@
 // expected-error@first.h:* {{'CompareLastImplAttribute' has different definitions in different modules; first difference is definition in module 'First.Hidden' found property 'lastImplAttribute' with 'direct' attribute}}
 // expected-note-re@second.h:* {{but in {{'Second'|definition here}} found property 'lastImplAttribute' with different 'direct' attribute}}
 #endif
+
+#if defined(FIRST)
+@interface CompareMatchingCategories: NSObject @end
+@interface CompareMatchingCategories(Matching)
+- (int)testMethod;
+@end
+
+@interface CompareMismatchingCategories1: NSObject @end
+@interface CompareMismatchingCategories1(Category1)
+- (void)presentMethod;
+@end
+@interface CompareMismatchingCategories2: NSObject @end
+@interface CompareMismatchingCategories2(Category2)
+@end
+
+@interface CompareDifferentCategoryNames: NSObject @end
+@interface CompareDifferentCategoryNames(CategoryFirst)
+- (void)firstMethod:(int)x;
+@end
+#elif defined(SECOND)
+@interface CompareMatchingCategories: NSObject @end
+@interface CompareMatchingCategories(Matching)
+- (int)testMethod;
+@end
+
+@interface CompareMismatchingCategories1: NSObject @end
+@interface CompareMismatchingCategories1(Category1)
+@end
+@interface CompareMismatchingCategories2: NSObject @end
+@interface CompareMismatchingCategories2(Category2)
+- (void)presentMethod;
+@end
+
+@interface CompareDifferentCategoryNames: NSObject @end
+@interface CompareDifferentCategoryNames(CategorySecond)
+- (void)secondMethod;
+@end
+#else
+CompareMatchingCategories *compareMatchingCategories; // no diagnostic
+CompareMismatchingCategories1 *compareMismatchingCategories1;
+#ifdef TEST_MODULAR
+// expected-warning@second.h:* {{duplicate definition of category 'Category1' on interface 'CompareMismatchingCategories1'}}
+// expected-note@first.h:* {{previous definition is here}}
+#endif
+CompareMismatchingCategories2 *compareMismatchingCategories2;
+#ifdef TEST_MODULAR
+// expected-warning@second.h:* {{duplicate definition of category 'Category2' on interface 'CompareMismatchingCategories2'}}
+// expected-note@first.h:* {{previous definition is here}}
+#endif
+CompareDifferentCategoryNames *compareDifferentCategoryNames; // no diagnostic
+#endif
Index: clang/lib/Serialization/ASTReaderDecl.cpp
===
--- clang/lib/Serialization/ASTReaderDecl.cpp
+++ clang/lib/Serialization/ASTReaderDecl.cpp
@@ -14,6 +14,7 @@
 #include "ASTCommon.h"
 #include "ASTReaderInternals.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTStructuralEquivalence.h"
 #include "clang/AST/Attr.h"
 #include "clang/AST/AttrIterator.h"
 #include "clang/AST/Decl.h"
@@ -4181,23 +4182,22 @@
   // Check for duplica

  1   2   >