[PATCH] D110869: [X86] Implement -fzero-call-used-regs option

2021-11-23 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 389101.
void added a comment.

WIP: Move register selection to a platform-generic place.

Not ready for review just yet.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110869

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/zero-call-used-regs.c
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/Sema/zero_call_used_regs.c
  llvm/include/llvm/CodeGen/MachineRegisterInfo.h
  llvm/include/llvm/CodeGen/TargetFrameLowering.h
  llvm/include/llvm/CodeGen/TargetRegisterInfo.h
  llvm/include/llvm/Support/CodeGen.h
  llvm/lib/CodeGen/MachineRegisterInfo.cpp
  llvm/lib/CodeGen/PrologEpilogInserter.cpp
  llvm/lib/Target/X86/X86FrameLowering.cpp
  llvm/lib/Target/X86/X86FrameLowering.h
  llvm/lib/Target/X86/X86RegisterInfo.cpp
  llvm/lib/Target/X86/X86RegisterInfo.h
  llvm/test/CodeGen/X86/zero-call-used-regs-all-arg.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-all-gpr-arg.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-all-gpr.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-all.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-fmod.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-skip.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-smoke-tests.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-used-arg.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-used-gpr-arg.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-used-gpr.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-used.ll

Index: llvm/test/CodeGen/X86/zero-call-used-regs-used.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/zero-call-used-regs-used.ll
@@ -0,0 +1,28 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu | FileCheck %s
+
+@result = dso_local global i32 0, align 4
+
+define dso_local i32 @foo(i32 returned %x) local_unnamed_addr #0 {
+; CHECK-LABEL: foo:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:movl %edi, %eax
+; CHECK-NEXT:xorl %edi, %edi
+; CHECK-NEXT:retq
+entry:
+  ret i32 %x
+}
+
+define dso_local i32 @main() local_unnamed_addr #1 {
+; CHECK-LABEL: main:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:movl $2, result(%rip)
+; CHECK-NEXT:xorl %eax, %eax
+; CHECK-NEXT:retq
+entry:
+  store volatile i32 2, i32* @result, align 4
+  ret i32 0
+}
+
+attributes #0 = { mustprogress nofree norecurse nosync nounwind readnone uwtable willreturn "frame-pointer"="none" "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" "zero-call-used-regs"="used" }
+attributes #1 = { nofree norecurse nounwind uwtable "frame-pointer"="none" "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" "zero-call-used-regs"="used" }
Index: llvm/test/CodeGen/X86/zero-call-used-regs-used-gpr.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/zero-call-used-regs-used-gpr.ll
@@ -0,0 +1,28 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu | FileCheck %s
+
+@result = dso_local global i32 0, align 4
+
+define dso_local i32 @foo(i32 returned %x) local_unnamed_addr #0 {
+; CHECK-LABEL: foo:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:movl %edi, %eax
+; CHECK-NEXT:xorl %edi, %edi
+; CHECK-NEXT:retq
+entry:
+  ret i32 %x
+}
+
+define dso_local i32 @main() local_unnamed_addr #1 {
+; CHECK-LABEL: main:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:movl $2, result(%rip)
+; CHECK-NEXT:xorl %eax, %eax
+; CHECK-NEXT:retq
+entry:
+  store volatile i32 2, i32* @result, align 4
+  ret i32 0
+}
+
+attributes #0 = { mustprogress nofree norecurse nosync nounwind readnone uwtable willreturn "frame-pointer"="none" "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" "zero-call-used-regs"="used-gpr" }
+attributes #1 = { nofree norecurse nounwind uwtable "frame-pointer"="none" "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" "zero-call-used-regs"="used-gpr" }
Index: llvm/test/CodeGen/X86/zero-call-used-regs-used-gpr-arg.ll
==

[PATCH] D114394: Compile-time computation of string attribute hashes

2021-11-23 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added inline comments.



Comment at: llvm/include/llvm/IR/Attributes.h:79
+  bool operator<(AttributeKey const &other) const {
+return strcmp(value_, other.value_) < 0;
+  }

Could order by size first here, then strncmp on equal sizes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114394

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


[PATCH] D114370: [clangd] IncludeCleaner: Attribute symbols from non self-contained headers to their parents

2021-11-23 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

thanks, LG in general, just a couple polishing touches




Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:146
+  //
+  // Returns true if the insertion into IDs took place.
+  bool insert(llvm::DenseSet &IDs, FileID ID, const SourceManager &SM,

this returns true even after inserting mainfile id, is that intended? I suppose 
it won't hurt too much, but means we'll go one step further for macros.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:155
+ ID != SM.getMainFileID() && FE &&
+ !PP.getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE);) {
+  ID = SM.getFileID(SM.getIncludeLoc(ID));

can you lift the 
[isSelfContainedHeader](https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/clangd/index/SymbolCollector.cpp#L282)
 into SourceCode.h and make use of it in both places (while updating the 
signature to accept a PP, through which you can access the SM).



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:162
+
+  void add(SourceLocation Loc, const SourceManager &SM,
+   const Preprocessor &PP) {

we already have access to `SM` from the members, can you do the same for `PP` 
(stash as a member during construction) rather than plumbing at each call?



Comment at: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp:350
+
+  auto ReferencedHeaders = translateToHeaderIDs(ReferencedFiles, Includes, SM);
+  std::vector ReferencedHeaderNames;

is this part of the check even relevant? let's drop this completely?



Comment at: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp:355
+  EXPECT_THAT(ReferencedHeaderNames,
+  ElementsAre(testPath("bar.h"), testPath("foo.h")));
+

maybe make this an `UnorderedElementsAre`, do we have any ordering guarantees 
in this API's contract?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114370

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


[PATCH] D114256: [clang-tidy] Fix crashing altera-struct-pack-align on invalid RecordDecls

2021-11-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

ping


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

https://reviews.llvm.org/D114256

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


[PATCH] D114082: [WIP] Normalize String Attributes

2021-11-23 Thread serge via Phabricator via cfe-commits
serge-sans-paille added a comment.

This diff is indeed very large. I reworked it in 
https://reviews.llvm.org/D114394 to capture the essence of it, on which we 
could then rebase this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114082

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


[PATCH] D114370: [clangd] IncludeCleaner: Attribute symbols from non self-contained headers to their parents

2021-11-23 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

The ReferencedFiles is designed to make add() as cheap as possible, and do any 
per-file logic after folding the fileIDs together.
This keeps that loop tighter and also isolates the complexity of the symbol vs 
file logic.
Any reason we can't do that here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114370

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


[PATCH] D113118: [clang][AST] Check context of record in structural equivalence.

2021-11-23 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 389111.
balazske added a comment.

Applied lint reformattings.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113118

Files:
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/unittests/AST/StructuralEquivalenceTest.cpp

Index: clang/unittests/AST/StructuralEquivalenceTest.cpp
===
--- clang/unittests/AST/StructuralEquivalenceTest.cpp
+++ clang/unittests/AST/StructuralEquivalenceTest.cpp
@@ -929,6 +929,136 @@
   EXPECT_TRUE(testStructuralMatch(First, Second));
 }
 
+struct StructuralEquivalenceRecordContextTest : StructuralEquivalenceTest {};
+
+TEST_F(StructuralEquivalenceRecordContextTest, NamespaceNoVsNamed) {
+  auto Decls = makeDecls("class X;", "namespace N { class X; }",
+Lang_CXX03, cxxRecordDecl());
+  EXPECT_FALSE(testStructuralMatch(Decls));
+}
+
+TEST_F(StructuralEquivalenceRecordContextTest, NamespaceNamedVsNamed) {
+  auto Decls = makeDecls("namespace A { class X; }",
+"namespace B { class X; }", Lang_CXX03,
+cxxRecordDecl());
+  EXPECT_FALSE(testStructuralMatch(Decls));
+}
+
+TEST_F(StructuralEquivalenceRecordContextTest, NamespaceAnonVsNamed) {
+  auto Decls = makeDecls("namespace { class X; }",
+"namespace N { class X; }", Lang_CXX03,
+cxxRecordDecl());
+  EXPECT_FALSE(testStructuralMatch(Decls));
+}
+
+TEST_F(StructuralEquivalenceRecordContextTest, NamespaceNoVsAnon) {
+  auto Decls = makeDecls("class X;", "namespace { class X; }",
+Lang_CXX03, cxxRecordDecl());
+  EXPECT_FALSE(testStructuralMatch(Decls));
+}
+
+TEST_F(StructuralEquivalenceRecordContextTest, NamespaceAnonVsAnon) {
+  auto Decls = makeDecls("namespace { class X; }",
+"namespace { class X; }", Lang_CXX03,
+cxxRecordDecl());
+  EXPECT_TRUE(testStructuralMatch(Decls));
+}
+
+TEST_F(StructuralEquivalenceRecordContextTest, NamespaceAnonVsAnonAnon) {
+  auto Decls = makeDecls("namespace { class X; }",
+"namespace { namespace { class X; } }",
+Lang_CXX03, cxxRecordDecl());
+  EXPECT_FALSE(testStructuralMatch(Decls));
+}
+
+TEST_F(StructuralEquivalenceRecordContextTest,
+   NamespaceNamedNamedVsNamedNamed) {
+  auto Decls = makeDecls(
+  "namespace A { namespace N { class X; } }",
+  "namespace B { namespace N { class X; } }", Lang_CXX03, cxxRecordDecl());
+  EXPECT_FALSE(testStructuralMatch(Decls));
+}
+
+TEST_F(StructuralEquivalenceRecordContextTest, NamespaceNamedVsInline) {
+  auto Decls = makeDecls(
+  "namespace A { namespace A { class X; } }",
+  "namespace A { inline namespace A { class X; } }", Lang_CXX17,
+  cxxRecordDecl());
+  EXPECT_FALSE(testStructuralMatch(Decls));
+}
+
+TEST_F(StructuralEquivalenceRecordContextTest, NamespaceInlineVsInline) {
+  auto Decls = makeDecls(
+  "namespace A { inline namespace A { class X; } }",
+  "namespace A { inline namespace B { class X; } }", Lang_CXX17,
+  cxxRecordDecl());
+  EXPECT_TRUE(testStructuralMatch(Decls));
+}
+
+TEST_F(StructuralEquivalenceRecordContextTest, NamespaceInlineTopLevel) {
+  auto Decls = makeDecls("inline namespace A { class X; } }",
+"inline namespace B { class X; } }",
+Lang_CXX17, cxxRecordDecl());
+  EXPECT_TRUE(testStructuralMatch(Decls));
+}
+
+TEST_F(StructuralEquivalenceRecordContextTest, TransparentContext) {
+  auto Decls = makeDecls("extern \"C\" { class X; }", "class X;",
+Lang_CXX03, cxxRecordDecl());
+  EXPECT_TRUE(testStructuralMatch(Decls));
+}
+
+TEST_F(StructuralEquivalenceRecordContextTest, TransparentContextNE) {
+  auto Decls = makeDecls("extern \"C\" { class X; }",
+"namespace { class X; }", Lang_CXX03,
+cxxRecordDecl());
+  EXPECT_FALSE(testStructuralMatch(Decls));
+}
+
+TEST_F(StructuralEquivalenceRecordContextTest, TransparentContextInNamespace) {
+  auto Decls = makeDecls(
+  "extern \"C\" { namespace N { class X; } }",
+  "namespace N { extern \"C\" { class X; } }", Lang_CXX03, cxxRecordDecl());
+  EXPECT_TRUE(testStructuralMatch(Decls));
+}
+
+TEST_F(StructuralEquivalenceTest, NamespaceOfRecordMember) {
+  auto Decls = makeDecls(
+  R"(
+  class X;
+  class Y { X* x; };
+  )",
+  R"(
+  namespace N { class X; }
+  class Y { N::X* x; };
+  )",
+  Lang_CXX03, cxxRecordDecl(hasName("Y")));
+  EXPECT_FALSE(testStructuralMatch(Decls));
+}
+
+TEST_F(StructuralEquivalenceTest, Struct

[PATCH] D110618: [HIPSPV][2/4] Add HIPSPV tool chain

2021-11-23 Thread Henry Linjamäki via Phabricator via cfe-commits
linjamaki updated this revision to Diff 389112.
linjamaki added a comment.

Combine options with append().


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110618

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/CMakeLists.txt
  clang/lib/Driver/ToolChains/AMDGPU.cpp
  clang/lib/Driver/ToolChains/HIPSPV.cpp
  clang/lib/Driver/ToolChains/HIPSPV.h

Index: clang/lib/Driver/ToolChains/HIPSPV.h
===
--- /dev/null
+++ clang/lib/Driver/ToolChains/HIPSPV.h
@@ -0,0 +1,102 @@
+//===--- HIPSPV.h - HIP ToolChain Implementations ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_HIPSPV_H
+#define LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_HIPSPV_H
+
+#include "SPIRV.h"
+#include "clang/Driver/Tool.h"
+#include "clang/Driver/ToolChain.h"
+
+namespace clang {
+namespace driver {
+namespace tools {
+namespace HIPSPV {
+
+// Runs llvm-link/opt/llc/lld, which links multiple LLVM bitcode, together with
+// device library, then compiles it to SPIR-V in a shared object.
+class LLVM_LIBRARY_VISIBILITY Linker : public Tool {
+public:
+  Linker(const ToolChain &TC) : Tool("HIPSPV::Linker", "hipspv-link", TC) {}
+
+  bool hasIntegratedCPP() const override { return false; }
+
+  void ConstructJob(Compilation &C, const JobAction &JA,
+const InputInfo &Output, const InputInfoList &Inputs,
+const llvm::opt::ArgList &TCArgs,
+const char *LinkingOutput) const override;
+
+private:
+  void constructLinkAndEmitSpirvCommand(Compilation &C, const JobAction &JA,
+const InputInfoList &Inputs,
+const InputInfo &Output,
+const llvm::opt::ArgList &Args) const;
+};
+
+} // namespace HIPSPV
+} // namespace tools
+
+namespace toolchains {
+
+class LLVM_LIBRARY_VISIBILITY HIPSPVToolChain final : public ToolChain {
+public:
+  HIPSPVToolChain(const Driver &D, const llvm::Triple &Triple,
+  const ToolChain &HostTC, const llvm::opt::ArgList &Args);
+
+  const llvm::Triple *getAuxTriple() const override {
+return &HostTC.getTriple();
+  }
+
+  void
+  addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
+llvm::opt::ArgStringList &CC1Args,
+Action::OffloadKind DeviceOffloadKind) const override;
+  void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const override;
+  CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const override;
+  void
+  AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
+llvm::opt::ArgStringList &CC1Args) const override;
+  void AddClangCXXStdlibIncludeArgs(
+  const llvm::opt::ArgList &Args,
+  llvm::opt::ArgStringList &CC1Args) const override;
+  void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs,
+   llvm::opt::ArgStringList &CC1Args) const override;
+  void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs,
+ llvm::opt::ArgStringList &CC1Args) const override;
+  llvm::SmallVector
+  getHIPDeviceLibs(const llvm::opt::ArgList &Args) const override;
+
+  SanitizerMask getSupportedSanitizers() const override;
+
+  VersionTuple
+  computeMSVCVersion(const Driver *D,
+ const llvm::opt::ArgList &Args) const override;
+
+  unsigned GetDefaultDwarfVersion() const override { return 5; }
+  bool IsIntegratedAssemblerDefault() const override { return true; }
+  bool IsMathErrnoDefault() const override { return false; }
+  bool useIntegratedAs() const override { return true; }
+  bool isCrossCompiling() const override { return true; }
+  bool isPICDefault() const override { return false; }
+  bool isPIEDefault(const llvm::opt::ArgList &Args) const override {
+return false;
+  }
+  bool isPICDefaultForced() const override { return false; }
+  bool SupportsProfiling() const override { return false; }
+
+  const ToolChain &HostTC;
+
+protected:
+  Tool *buildLinker() const override;
+};
+
+} // end namespace toolchains
+} // end namespace driver
+} // end namespace clang
+
+#endif // LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_HIPSPV_H
Index: clang/lib/Driver/ToolChains/HIPSPV.cpp
===
--- /dev/null
+++ clang/lib/Driver/ToolChains/HIPSPV.cpp
@@ -0,0 +1,288 @@
+//===--- HIPSPV.cpp - HIPSPV ToolChain Implementation ---*- C++ -*-===//
+//
+// Part of the LLVM Pro

[PATCH] D110622: [HIPSPV][3/4] Enable SPIR-V emission for HIP

2021-11-23 Thread Henry Linjamäki via Phabricator via cfe-commits
linjamaki updated this revision to Diff 389114.
linjamaki marked 2 inline comments as done.
linjamaki added a comment.

Update a driver test case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110622

Files:
  clang/include/clang/Basic/Cuda.h
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Cuda.cpp
  clang/lib/Basic/Targets/NVPTX.cpp
  clang/lib/Basic/Targets/NVPTX.h
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/Inputs/hipspv-dev-lib/a/a.bc
  clang/test/Driver/Inputs/hipspv-dev-lib/b/b.bc
  clang/test/Driver/Inputs/hipspv-dev-lib/hipspv-spirv64.bc
  clang/test/Driver/Inputs/hipspv/bin/.hipVersion
  clang/test/Driver/Inputs/hipspv/lib/hip-device-lib/hipspv-spirv64.bc
  clang/test/Driver/Inputs/hipspv/lib/libLLVMHipSpvPasses.so
  clang/test/Driver/Inputs/pass-plugin.so
  clang/test/Driver/hipspv-device-libs.hip
  clang/test/Driver/hipspv-pass-plugin.hip
  clang/test/Driver/hipspv-toolchain-rdc.hip
  clang/test/Driver/hipspv-toolchain.hip
  clang/test/Driver/invalid-offload-options.cpp

Index: clang/test/Driver/invalid-offload-options.cpp
===
--- /dev/null
+++ clang/test/Driver/invalid-offload-options.cpp
@@ -0,0 +1,24 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// UNSUPPORTED: system-windows
+
+// RUN: %clang -### -x hip -target x86_64-linux-gnu --offload= \
+// RUN:   --hip-path=%S/Inputs/hipspv -nogpuinc -nogpulib %s \
+// RUN: 2>&1 | FileCheck --check-prefix=INVALID-TARGET %s
+// RUN: %clang -### -x hip -target x86_64-linux-gnu --offload=foo \
+// RUN:   --hip-path=%S/Inputs/hipspv -nogpuinc -nogpulib %s \
+// RUN: 2>&1 | FileCheck --check-prefix=INVALID-TARGET %s
+
+// INVALID-TARGET: error: Invalid or unsupported offload target: '{{.*}}'
+
+// RUN: %clang -### -x hip -target x86_64-linux-gnu --offload=foo,bar \
+// RUN:   --hip-path=%S/Inputs/hipspv -nogpuinc -nogpulib %s \
+// RUN: 2>&1 | FileCheck --check-prefix=TOO-MANY-TARGETS %s
+
+// TOO-MANY-TARGETS: error: Only one offload target is supported in HIP.
+
+// RUN: %clang -### -x hip -target x86_64-linux-gnu -nogpuinc -nogpulib \
+// RUN:   --offload=amdgcn-amd-amdhsa --offload-arch=gfx900 %s \
+// RUN: 2>&1 | FileCheck --check-prefix=OFFLOAD-ARCH-MIX %s
+
+// OFFLOAD-ARCH-MIX: error: option '--offload-arch' cannot be specified with '--offload'
Index: clang/test/Driver/hipspv-toolchain.hip
===
--- /dev/null
+++ clang/test/Driver/hipspv-toolchain.hip
@@ -0,0 +1,37 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// UNSUPPORTED: system-windows
+
+// RUN: %clang -### -target x86_64-linux-gnu --offload=spirv64 \
+// RUN:   --hip-path=%S/Inputs/hipspv -nohipwrapperinc %s \
+// RUN: 2>&1 | FileCheck %s
+
+// CHECK: [[CLANG:".*clang.*"]] "-cc1" "-triple" "spirv64"
+// CHECK-SAME: "-aux-triple" "{{.*}}" "-emit-llvm-bc"
+// CHECK-SAME: "-fcuda-is-device"
+// CHECK-SAME: "-fcuda-allow-variadic-functions"
+// CHECK-SAME: "-mlink-builtin-bitcode" {{".*/hipspv/lib/hip-device-lib/hipspv-spirv64.bc"}}
+// CHECK-SAME: "-isystem" {{".*/hipspv/include"}}
+// CHECK-SAME: "-fhip-new-launch-api"
+// CHECK-SAME: "-o" [[DEV_BC:".*bc"]]
+// CHECK-SAME: "-x" "hip"
+
+// CHECK: {{".*llvm-link"}} [[DEV_BC]] "-o" [[LINK_BC:".*bc"]]
+
+// CHECK: {{".*opt"}} [[LINK_BC]] "-load-pass-plugin"
+// CHECK-SAME: {{".*/hipspv/lib/libLLVMHipSpvPasses.so"}}
+// CHECK-SAME: "-passes=hip-post-link-passes" "-o" [[LOWER_BC:".*bc"]]
+
+// CHECK: {{".*llvm-spirv"}} "--spirv-max-version=1.1" "--spirv-ext=+all"
+// CHECK-SAME: [[LOWER_BC]] "-o" "[[SPIRV_OUT:.*out]]"
+
+// CHECK: {{".*clang-offload-bundler"}} "-type=o" "-bundle-align=4096"
+// CHECK-SAME: "-targets=host-x86_64-unknown-linux,hip-spirv64generic"
+// CHECK-SAME: "-inputs={{.*}},[[SPIRV_OUT]]" "-outputs=[[BUNDLE:.*hipfb]]"
+
+// CHECK: [[CLANG]] "-cc1" "-triple" {{".*"}} "-aux-triple" "spirv64"
+// CHECK-SAME: "-emit-obj"
+// CHECK-SAME: "-fcuda-include-gpubinary" "[[BUNDLE]]"
+// CHECK-SAME: "-o" [[OBJ_HOST:".*o"]] "-x" "hip"
+
+// CHECK: {{".*ld.*"}} {{.*}}[[OBJ_HOST]]
Index: clang/test/Driver/hipspv-toolchain-rdc.hip
===
--- /dev/null
+++ clang/test/Driver/hipspv-toolchain-rdc.hip
@@ -0,0 +1,63 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// UNSUPPORTED: system-windows
+
+// RUN: %clang -### -x hip -target x86_64-linux-gnu --offload=spirv64 \
+// RUN:   -fgpu-rdc --hip-path=%S/Inputs/hipspv -nohipwrapperinc \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck %s
+
+// Emit objects for host side path
+// CHECK: [[CLANG:".*clang.*"]] "-cc1" "-triple" "x86_64-unknown-linux-gnu"

[PATCH] D114418: [clang][ASTImporter] Update lookup table correctly at deduction guides.

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

Declaration context of template parameters of a FunctionTemplateDecl
may be different for each one parameter if the template is a
deduction guide. This case is handled correctly after this change.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114418

Files:
  clang/include/clang/AST/ASTImporterLookupTable.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/ASTImporterLookupTable.cpp
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -7329,6 +7329,34 @@
   EXPECT_EQ(*ShadowI, ToUsingShadowF2);
 }
 
+AST_MATCHER_P(FunctionTemplateDecl, templateParameterCountIs, unsigned, Cnt) {
+  return Node.getTemplateParameters()->size() == Cnt;
+}
+
+TEST_P(ASTImporterOptionSpecificTestBase, ImportDeductionGuide) {
+  TranslationUnitDecl *FromTU = getTuDecl(
+  R"(
+  template class A { };
+  template class B {
+  template> B(T1);
+  };
+  template
+  B(T, T) -> B;
+  )",
+  Lang_CXX17);
+
+  // Get the implicit deduction guide for (non-default) constructor of 'B'.
+  auto *FromDG1 = FirstDeclMatcher().match(
+  FromTU, functionTemplateDecl(templateParameterCountIs(3)));
+  // User defined deduction guide.
+  auto *FromDG2 = FirstDeclMatcher().match(
+  FromTU, cxxDeductionGuideDecl(unless(isImplicit(;
+
+  // Check if the import does not crash.
+  (void)Import(FromDG1, Lang_CXX17);
+  (void)Import(FromDG2, Lang_CXX17);
+}
+
 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterLookupTableTest,
  DefaultTestValuesForRunOptions);
 
Index: clang/lib/AST/ASTImporterLookupTable.cpp
===
--- clang/lib/AST/ASTImporterLookupTable.cpp
+++ clang/lib/AST/ASTImporterLookupTable.cpp
@@ -140,6 +140,11 @@
   add(ND);
 }
 
+void ASTImporterLookupTable::updateForced(NamedDecl *ND, DeclContext *OldDC) {
+  LookupTable[OldDC][ND->getDeclName()].remove(ND);
+  add(ND);
+}
+
 ASTImporterLookupTable::LookupResult
 ASTImporterLookupTable::lookup(DeclContext *DC, DeclarationName Name) const {
   auto DCI = LookupTable.find(DC->getPrimaryContext());
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -6066,20 +6066,27 @@
   if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl()))
 return std::move(Err);
 
-  // Template parameters of the ClassTemplateDecl and FunctionTemplateDecl are
-  // shared, if the FunctionTemplateDecl is a deduction guide for the class.
-  // At import the ClassTemplateDecl object is always created first (FIXME: is
-  // this really true?) because the dependency, then the FunctionTemplateDecl.
-  // The DeclContext of the template parameters is changed when the
-  // FunctionTemplateDecl is created, but was set already when the class
-  // template was created. So here it is not the TU (default value) any more.
-  // FIXME: The DeclContext of the parameters is now set finally to the
-  // CXXDeductionGuideDecl object that was imported later. This may not be the
-  // same that is in the original AST, specially if there are multiple deduction
-  // guides.
-  DeclContext *OldParamDC = nullptr;
-  if (Params->size() > 0)
-OldParamDC = Params->getParam(0)->getDeclContext();
+  // At creation of the template the template parameters are "adopted"
+  // (DeclContext is changed). After this possible change the lookup table
+  // must be updated.
+  // At deduction guides the DeclContext of the template parameters may be
+  // different from what we would expect, it may be the class template, or a
+  // probably different CXXDeductionGuideDecl. This may come from the fact that
+  // the template parameter objects may be shared between deduction guides or
+  // the class template, and at creation of multiple FunctionTemplateDecl
+  // objects (for deduction guides) the same parameters are re-used. The
+  // "adoption" happens multiple times with different parent, even recursively
+  // for TemplateTemplateParmDecl. The same happens at import when the
+  // FunctionTemplateDecl objects are created, but in different order. In this
+  // way DeclContext of these template parameters may change relative to the
+  // "from" context. Because these DeclContext values look already not stable
+  // and unimportant this change looks acceptable.
+  // For these reasons the old DeclContext must be saved to change the lookup
+  // table later.
+  SmallVector OldParamDC

[PATCH] D113251: [analyzer][doc] Add user documenation for taint analysis

2021-11-23 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 389117.
gamesh411 marked 15 inline comments as done.
gamesh411 added a comment.

tidy up based on comments from whispy


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113251

Files:
  clang/docs/analyzer/checkers.rst
  clang/docs/analyzer/user-docs/TaintAnalysisConfiguration.rst

Index: clang/docs/analyzer/user-docs/TaintAnalysisConfiguration.rst
===
--- clang/docs/analyzer/user-docs/TaintAnalysisConfiguration.rst
+++ clang/docs/analyzer/user-docs/TaintAnalysisConfiguration.rst
@@ -2,15 +2,16 @@
 Taint Analysis Configuration
 
 
-Clang Static Analyzer uses taint analysis to detect security-related issues in code.
-The backbone of taint analysis in Clang is the `GenericTaintChecker`, which the user can access via the :ref:`alpha-security-taint-TaintPropagation` checker alias and this checker has a default taint-related configuration.
-The checker also provides a configuration interface for extending the default settings by providing a configuration file in `YAML `_ format.
+The Clang Static Analyzer uses taint analysis to detect security-related issues in code.
+The backbone of taint analysis in the Clang SA is the `GenericTaintChecker`, which the user can access via the :ref:`alpha-security-taint-TaintPropagation` checker alias and this checker has a default taint-related configuration.
+The built-in default settings are defined in code, and they are always in effect once the checker is enabled, either directly or via the alias.
+The checker also provides a configuration interface for extending the default settings by providing a configuration file in `YAML `_ format.
 This documentation describes the syntax of the configuration file and gives the informal semantics of the configuration options.
 
 .. contents::
:local:
 
-.. _taint-configuration-overview
+.. _clangsa-taint-configuration-overview:
 
 Overview
 
@@ -18,61 +19,74 @@
 Taint analysis works by checking for the occurrence of special operations during the symbolic execution of the program.
 Taint analysis defines sources, sinks, and propagation rules. It identifies errors by detecting a flow of information that originates from a taint source, reaches a taint sink, and propagates through the program paths via propagation rules.
 A source, sink, or an operation that propagates taint is mainly domain-specific knowledge, but there are some built-in defaults provided by :ref:`alpha-security-taint-TaintPropagation`.
+It is possible to express that a statement sanitizes tainted values by providing a ``Filters`` section in the external configuration (see :ref:`clangsa-taint-configuration-example` and :ref:`clangsa-taint-filter-details`).
+There are no default filters defined in the built-in settings.
 The checker's documentation also specifies how to provide a custom taint configuration with command-line options.
 
-.. _taint-configuration-example:
+.. _clangsa-taint-configuration-example:
 
 Example configuration file
 __
 
 .. code-block:: yaml
 
+  # The entries that specify arguments use 0 based indexing when specifying
+  # input arguments, and -1 is used to denote the return value.
+
   Filters:
-# signature:
-# void cleanse_first_arg(int* arg)
+# Filter functions
+# Taint is sanitized when tainted variables are pass arguments to filters.
+
+# Filter function
+#   void cleanse_first_arg(int* arg)
 #
-# example:
-# int x; // x is tainted
-# cleanse_first_arg(&x); // x is not tainted anymore
+# Result example:
+#   int x; // x is tainted
+#   cleanse_first_arg(&x); // x is not tainted after the call
 - Name: cleanse_first_arg
   Args: [0]
 
   Propagations:
-  # sources:
-  # The omission of SrcArgs key indicates unconditional taint propagation,
-  # which is conceptually what a source does.
-# signature:
-# size_t fread(void *ptr, size_t size, size_t nmemb, FILE * stream)
+# Source functions
+# The omission of SrcArgs key indicates unconditional taint propagation,
+# which is conceptually what a source does.
+
+# Source function
+#   size_t fread(void *ptr, size_t size, size_t nmemb, FILE * stream)
 #
-# example:
-# FILE* f = fopen("file.txt");
-# char buf[1024];
-# size_t read = fread(buf, sizeof(buf[0]), sizeof(buf)/sizeof(buf[0]), f);
-# // both read and buf are tainted
+# Result example:
+#   FILE* f = fopen("file.txt");
+#   char buf[1024];
+#   size_t read = fread(buf, sizeof(buf[0]), sizeof(buf)/sizeof(buf[0]), f);
+#   // both read and buf are tainted
 - Name: fread
   DstArgs: [0, -1]
 
-  # propagations:
-  # The presence of SrcArgs key indicates conditional taint propagation,
-  

[PATCH] D110618: [HIPSPV][2/4] Add HIPSPV tool chain

2021-11-23 Thread Henry Linjamäki via Phabricator via cfe-commits
linjamaki updated this revision to Diff 389118.
linjamaki added a comment.

Retry push changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110618

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/CMakeLists.txt
  clang/lib/Driver/ToolChains/AMDGPU.cpp
  clang/lib/Driver/ToolChains/HIPSPV.cpp
  clang/lib/Driver/ToolChains/HIPSPV.h

Index: clang/lib/Driver/ToolChains/HIPSPV.h
===
--- /dev/null
+++ clang/lib/Driver/ToolChains/HIPSPV.h
@@ -0,0 +1,102 @@
+//===--- HIPSPV.h - HIP ToolChain Implementations ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_HIPSPV_H
+#define LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_HIPSPV_H
+
+#include "SPIRV.h"
+#include "clang/Driver/Tool.h"
+#include "clang/Driver/ToolChain.h"
+
+namespace clang {
+namespace driver {
+namespace tools {
+namespace HIPSPV {
+
+// Runs llvm-link/opt/llc/lld, which links multiple LLVM bitcode, together with
+// device library, then compiles it to SPIR-V in a shared object.
+class LLVM_LIBRARY_VISIBILITY Linker : public Tool {
+public:
+  Linker(const ToolChain &TC) : Tool("HIPSPV::Linker", "hipspv-link", TC) {}
+
+  bool hasIntegratedCPP() const override { return false; }
+
+  void ConstructJob(Compilation &C, const JobAction &JA,
+const InputInfo &Output, const InputInfoList &Inputs,
+const llvm::opt::ArgList &TCArgs,
+const char *LinkingOutput) const override;
+
+private:
+  void constructLinkAndEmitSpirvCommand(Compilation &C, const JobAction &JA,
+const InputInfoList &Inputs,
+const InputInfo &Output,
+const llvm::opt::ArgList &Args) const;
+};
+
+} // namespace HIPSPV
+} // namespace tools
+
+namespace toolchains {
+
+class LLVM_LIBRARY_VISIBILITY HIPSPVToolChain final : public ToolChain {
+public:
+  HIPSPVToolChain(const Driver &D, const llvm::Triple &Triple,
+  const ToolChain &HostTC, const llvm::opt::ArgList &Args);
+
+  const llvm::Triple *getAuxTriple() const override {
+return &HostTC.getTriple();
+  }
+
+  void
+  addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
+llvm::opt::ArgStringList &CC1Args,
+Action::OffloadKind DeviceOffloadKind) const override;
+  void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const override;
+  CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const override;
+  void
+  AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
+llvm::opt::ArgStringList &CC1Args) const override;
+  void AddClangCXXStdlibIncludeArgs(
+  const llvm::opt::ArgList &Args,
+  llvm::opt::ArgStringList &CC1Args) const override;
+  void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs,
+   llvm::opt::ArgStringList &CC1Args) const override;
+  void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs,
+ llvm::opt::ArgStringList &CC1Args) const override;
+  llvm::SmallVector
+  getHIPDeviceLibs(const llvm::opt::ArgList &Args) const override;
+
+  SanitizerMask getSupportedSanitizers() const override;
+
+  VersionTuple
+  computeMSVCVersion(const Driver *D,
+ const llvm::opt::ArgList &Args) const override;
+
+  unsigned GetDefaultDwarfVersion() const override { return 5; }
+  bool IsIntegratedAssemblerDefault() const override { return true; }
+  bool IsMathErrnoDefault() const override { return false; }
+  bool useIntegratedAs() const override { return true; }
+  bool isCrossCompiling() const override { return true; }
+  bool isPICDefault() const override { return false; }
+  bool isPIEDefault(const llvm::opt::ArgList &Args) const override {
+return false;
+  }
+  bool isPICDefaultForced() const override { return false; }
+  bool SupportsProfiling() const override { return false; }
+
+  const ToolChain &HostTC;
+
+protected:
+  Tool *buildLinker() const override;
+};
+
+} // end namespace toolchains
+} // end namespace driver
+} // end namespace clang
+
+#endif // LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_HIPSPV_H
Index: clang/lib/Driver/ToolChains/HIPSPV.cpp
===
--- /dev/null
+++ clang/lib/Driver/ToolChains/HIPSPV.cpp
@@ -0,0 +1,283 @@
+//===--- HIPSPV.cpp - HIPSPV ToolChain Implementation ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under

[PATCH] D113251: [analyzer][doc] Add user documenation for taint analysis

2021-11-23 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 added inline comments.



Comment at: clang/docs/analyzer/checkers.rst:2341-2342
+
+Default propagations defined by `GenericTaintChecker`:
+``atoi``, ``atol``, ``atoll``, ``fgetc``, ``fgetln``, ``fgets``, ``fscanf``, 
``sscanf``, ``getc``, ``getc_unlocked``, ``getdelim``, ``getline``, ``getw``, 
``pread``, ``read``, ``strchr``, ``strrchr``, ``tolower``, ``toupper``
+

whisperity wrote:
> What does it mean that these are "default propagations"? That taint passes 
> through calls to them trivially?
Added just 2 sentences about what default means.
Please see them a bit further up in the new version of the patch. 



Comment at: clang/docs/analyzer/checkers.rst:2345
+Default sinks defined in `GenericTaintChecker`:
+``printf``, ``setproctitle``, ``system``, ``popen``, ``execl``, ``execle``, 
``execlp``, ``execv``, ``execvp``, ``execvP``, ``execve``, ``dlopen``, 
``memcpy``, ``memmove``, ``strncpy``, ``strndup``, ``malloc``, ``calloc``, 
``alloca``, ``memccpy``, ``realloc``, ``bcopy``
+

whisperity wrote:
> `execvp` and `execvP`? What is the capital `P` for? I can't find this 
> overload in the POSIX docs.
I have found a refence to this function inside `TargetLibraryInfoTest.cpp`.
```
 926   │   case LibFunc_execv:
 927   │   case LibFunc_execvp:
 928   │ return (NumParams == 2 && FTy.getParamType(0)->isPointerTy() &&
 929   │ FTy.getParamType(1)->isPointerTy() &&
 930   │ FTy.getReturnType()->isIntegerTy(32));
 931   │   case LibFunc_execvP:
 932   │   case LibFunc_execvpe:
 933   │   case LibFunc_execve:
 934   │ return (NumParams == 3 && FTy.getParamType(0)->isPointerTy() &&
 935   │ FTy.getParamType(1)->isPointerTy() &&
 936   │ FTy.getParamType(2)->isPointerTy() &&
 937   │ FTy.getReturnType()->isIntegerTy(32));
```
It seems like an OSX-specific spelling and seems like it has the semantics of 
`execve`.
During the implementation of this patch, I just collected the references to 
functions inside  `GenericTaintChecker.cpp`.



Comment at: clang/docs/analyzer/user-docs/TaintAnalysisConfiguration.rst:5
+
+Clang Static Analyzer uses taint analysis to detect security-related issues in 
code.
+The backbone of taint analysis in Clang is the `GenericTaintChecker`, which 
the user can access via the :ref:`alpha-security-taint-TaintPropagation` 
checker alias and this checker has a default taint-related configuration.

whisperity wrote:
> whisperity wrote:
> > //The// Clang Static [...]?
> uses, or can use?
For brevity and clarity, I will leave it at `uses`, it is just a generic 
statement about the availability of taint analysis as a method, and I think it 
would not improve the understanding to change it to `can use`. IMHO it is 
implicit, and `can use` would make people wonder as to what does Clang need to 
use it etc.



Comment at: clang/docs/analyzer/user-docs/TaintAnalysisConfiguration.rst:6
+Clang Static Analyzer uses taint analysis to detect security-related issues in 
code.
+The backbone of taint analysis in Clang is the `GenericTaintChecker`, which 
the user can access via the :ref:`alpha-security-taint-TaintPropagation` 
checker alias and this checker has a default taint-related configuration.
+The checker also provides a configuration interface for extending the default 
settings by providing a configuration file in `YAML `_ 
format.

whisperity wrote:
> whisperity wrote:
> > Clang -> Clang SA / CSA?
> So the checker has the defaults all the time, or only by enabling the alias 
> can I get the defaults?
Good point, added a line to clarify this.



Comment at: clang/docs/analyzer/user-docs/TaintAnalysisConfiguration.rst:23
+
+.. _taint-configuration-example:
+

whisperity wrote:
> AFAIK, RST anchors are global identifiers for the project, so maybe we should 
> take care in adding "clang-sa" or some other sort of namespaceing...
> 
> (Although this might depend on how exactly the docs are built!)
added `clangsa-` prefix



Comment at: clang/docs/analyzer/user-docs/TaintAnalysisConfiguration.rst:30
+
+  Filters:
+# signature:

whisperity wrote:
> //Filters// are not mentioned earlier.
Added a mention with references in the Overview section.



Comment at: clang/docs/analyzer/user-docs/TaintAnalysisConfiguration.rst:31-36
+# signature:
+# void cleanse_first_arg(int* arg)
+#
+# example:
+# int x; // x is tainted
+# cleanse_first_arg(&x); // x is not tainted anymore

whisperity wrote:
> If none of the comments themselves are just commented out ("optional") keys 
> in the YAML, it would be better readable with a bit of formatting.
Reformatted the examples section according to your suggestions.



Comment at: clang/docs/analyzer/user-docs/TaintAnalysisCo

[PATCH] D110618: [HIPSPV][2/4] Add HIPSPV tool chain

2021-11-23 Thread Henry Linjamäki via Phabricator via cfe-commits
linjamaki marked 4 inline comments as done.
linjamaki added a comment.

Thanks for the review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110618

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


[PATCH] D110549: [HIPSPV][1/4] Refactor HIP tool chain

2021-11-23 Thread Henry Linjamäki via Phabricator via cfe-commits
linjamaki added a comment.

Thanks for the review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110549

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


[PATCH] D113250: [clang][driver] Add -fplugin-arg- to pass arguments to plugins

2021-11-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder marked 13 inline comments as done.
tbaeder added inline comments.



Comment at: clang/test/Driver/plugin-driver-args.cpp:11
+// Dashes cannot be part of the plugin name here
+// RUN: %clang -fplugin=%llvmshlibdir/CallSuperAttr%pluginext 
-fplugin-arg-call_super_plugin-help-long -fsyntax-only %s 2>&1 -### | FileCheck 
%s --check-prefix=CHECK-CMD
+// CHECK-CMD: "-plugin-arg-call_super_plugin" "help-long"

MaskRay wrote:
> I assume that you have checked `// REQUIRES: plugins, examples` is not 
> needed, i.e. the test still passes if -DLLVM_ENABLE_PLUGINS=off
I did, but I didn't delete the local `CallSuperAttr.so`. After doing that, they 
failed. I hope using `-###` as well here is fine.


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

https://reviews.llvm.org/D113250

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


[PATCH] D113250: [clang][driver] Add -fplugin-arg- to pass arguments to plugins

2021-11-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 389121.
tbaeder marked an inline comment as done.
tbaeder added a comment.

Addressed review comments and fixed the tests


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

https://reviews.llvm.org/D113250

Files:
  clang/docs/ClangPlugins.rst
  clang/docs/ReleaseNotes.rst
  clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/plugin-driver-args.cpp
  clang/test/Frontend/plugin-call-super.cpp

Index: clang/test/Frontend/plugin-call-super.cpp
===
--- clang/test/Frontend/plugin-call-super.cpp
+++ clang/test/Frontend/plugin-call-super.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang -fplugin=%llvmshlibdir/CallSuperAttr%pluginext -fsyntax-only -Xclang -verify=callsuper %s
-// RUN: %clang -fplugin=%llvmshlibdir/CallSuperAttr%pluginext -DBAD_CALLSUPER -fsyntax-only -Xclang -verify=badcallsuper %s
+// RUN: %clang_cc1 -load %llvmshlibdir/CallSuperAttr%pluginext -fsyntax-only -verify=callsuper %s
+// RUN: %clang_cc1 -load %llvmshlibdir/CallSuperAttr%pluginext -DBAD_CALLSUPER -fsyntax-only -verify=badcallsuper %s
 // REQUIRES: plugins, examples
 
 // callsuper-no-diagnostics
Index: clang/test/Driver/plugin-driver-args.cpp
===
--- /dev/null
+++ clang/test/Driver/plugin-driver-args.cpp
@@ -0,0 +1,22 @@
+/// Test passing args to plugins via the clang driver and -fplugin-arg
+// RUN: %clang -fplugin=%llvmshlibdir/CallSuperAttr%pluginext -fplugin-arg-call_super_plugin-help -fsyntax-only -### %s 2>&1 | FileCheck %s
+
+// CHECK: "-load"
+// CHECK-SAME: CallSuperAttr
+// CHECK-SAME: "-plugin-arg-call_super_plugin"
+// CHECK-SAME: "help"
+
+/// Check that dashed-args get forwarded like this to the plugin.
+/// Dashes cannot be part of the plugin name here
+// RUN: %clang -fplugin=%llvmshlibdir/CallSuperAttr%pluginext -fplugin-arg-call_super_plugin-help-long -fsyntax-only %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-CMD
+// CHECK-CMD: "-plugin-arg-call_super_plugin" "help-long"
+
+/// Error handling for -fplugin-arg-
+// RUN: %clang -fplugin=%llvmshlibdir/CallSuperAttr%pluginext -fplugin-arg- -fsyntax-only %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PLUGIN-NAME
+// CHECK-NO-PLUGIN-NAME: missing plugin name in -fplugin-arg-
+
+// RUN: %clang -fplugin=%llvmshlibdir/CallSuperAttr%pluginext -fplugin-arg-testname -fsyntax-only %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PLUGIN-ARG1
+// CHECK-NO-PLUGIN-ARG1: missing plugin argument for plugin testname in -fplugin-arg-testname
+
+// RUN: %clang -fplugin=%llvmshlibdir/CallSuperAttr%pluginext -fplugin-arg-testname- -fsyntax-only %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-PLUGIN-ARG2
+// CHECK-NO-PLUGIN-ARG2: missing plugin argument for plugin testname in -fplugin-arg-testname-
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6660,6 +6660,35 @@
 A->claim();
   }
 
+  // Turn -fplugin-arg-pluginname-key=value into
+  // -plugin-arg-pluginname key=value
+  // GCC has an actual plugin_argument struct with key/value pairs that it
+  // passes to its plugins, but we don't, so just pass it on as-is.
+  //
+  // The syntax for -fplugin-arg- is ambiguous if both plugin name and
+  // argument key are allowed to contain dashes. GCC therefore only
+  // allows dashes in the key. We do the same.
+  for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
+auto ArgValue = StringRef(A->getValue());
+auto FirstDashIndex = ArgValue.find('-');
+StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
+StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
+
+A->claim();
+if (FirstDashIndex == StringRef::npos || Arg.empty()) {
+  if (PluginName.empty()) {
+D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
+  } else {
+D.Diag(diag::warn_drv_missing_plugin_arg)
+<< PluginName << A->getAsString(Args);
+  }
+  continue;
+}
+
+CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
+CmdArgs.push_back(Args.MakeArgString(Arg));
+  }
+
   // Forward -fpass-plugin=name.so to -cc1.
   for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
 CmdArgs.push_back(
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2504,6 +2504,9 @@
   NegFlag>;
 def fplugin_EQ : Joined<["-"], "fplugin=">, Group, Flags<[NoXarchOption]>, MetaVarName<"">,
   HelpText<"Load the named plugin (dynamic shared object)">;
+def fplugin_arg : Joined<["-"], "fp

[PATCH] D114421: [asan] Add support for disable_sanitizer_instrumentation attribute

2021-11-23 Thread Alexander Potapenko via Phabricator via cfe-commits
glider created this revision.
glider added reviewers: melver, vitalybuka.
glider requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

For ASan this will effectively serve as a synonym for
__attribute__((no_sanitize("address")))


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114421

Files:
  clang/docs/AddressSanitizer.rst
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/SanitizerMetadata.cpp
  clang/test/CodeGen/address-safety-attr-flavors.cpp
  clang/test/CodeGen/asan-globals.cpp

Index: clang/test/CodeGen/asan-globals.cpp
===
--- clang/test/CodeGen/asan-globals.cpp
+++ clang/test/CodeGen/asan-globals.cpp
@@ -10,6 +10,7 @@
 int global;
 int dyn_init_global = global;
 int __attribute__((no_sanitize("address"))) attributed_global;
+int __attribute__((disable_sanitizer_instrumentation)) disable_instrumentation_global;
 int blacklisted_global;
 
 int __attribute__((section("__DATA, __common"))) sectioned_global; // KASAN - ignore globals in a section
@@ -50,7 +51,7 @@
 // UWTABLE: attributes #[[#ATTR]] = { nounwind uwtable }
 // UWTABLE: ![[#]] = !{i32 7, !"uwtable", i32 1}
 
-// CHECK: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], ![[GLOBAL:[0-9]+]], ![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], ![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], ![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], ![[LITERAL:[0-9]+]]}
+// CHECK: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], ![[GLOBAL:[0-9]+]], ![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], ![[DISABLE_INSTR_GLOBAL:[0-9]+]], ![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], ![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], ![[LITERAL:[0-9]+]]}
 // CHECK: ![[EXTRA_GLOBAL]] = !{{{.*}} ![[EXTRA_GLOBAL_LOC:[0-9]+]], !"extra_global", i1 false, i1 false}
 // CHECK: ![[EXTRA_GLOBAL_LOC]] = !{!"{{.*}}extra-source.cpp", i32 1, i32 5}
 // CHECK: ![[GLOBAL]] = !{{{.*}} ![[GLOBAL_LOC:[0-9]+]], !"global", i1 false, i1 false}
@@ -58,22 +59,24 @@
 // CHECK: ![[DYN_INIT_GLOBAL]] = !{{{.*}} ![[DYN_INIT_LOC:[0-9]+]], !"dyn_init_global", i1 true, i1 false}
 // CHECK: ![[DYN_INIT_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 11, i32 5}
 // CHECK: ![[ATTR_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
+// CHECK: ![[DISABLE_INSTR_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
 // CHECK: ![[BLACKLISTED_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
 // CHECK: ![[SECTIONED_GLOBAL]] = !{{{.*}} ![[SECTIONED_GLOBAL_LOC:[0-9]+]], !"sectioned_global", i1 false, i1 false}
-// CHECK: ![[SECTIONED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 15, i32 50}
+// CHECK: ![[SECTIONED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 16, i32 50}
 // CHECK: ![[SPECIAL_GLOBAL]] = !{{{.*}} ![[SPECIAL_GLOBAL_LOC:[0-9]+]], !"__special_global", i1 false, i1 false}
-// CHECK: ![[SPECIAL_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 17, i32 5}
+// CHECK: ![[SPECIAL_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 18, i32 5}
 // CHECK: ![[STATIC_VAR]] = !{{{.*}} ![[STATIC_LOC:[0-9]+]], !"static_var", i1 false, i1 false}
-// CHECK: ![[STATIC_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 21, i32 14}
+// CHECK: ![[STATIC_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 22, i32 14}
 // CHECK: ![[LITERAL]] = !{{{.*}} ![[LITERAL_LOC:[0-9]+]], !"", i1 false, i1 false}
-// CHECK: ![[LITERAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 22, i32 25}
+// CHECK: ![[LITERAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 23, i32 25}
 
-// BLACKLIST-SRC: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], ![[GLOBAL:[0-9]+]], ![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], ![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], ![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], ![[LITERAL:[0-9]+]]}
+// BLACKLIST-SRC: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], ![[GLOBAL:[0-9]+]], ![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], ![[DISABLE_INSTR_GLOBAL:[0-9]+]], ![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], ![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], ![[LITERAL:[0-9]+]]}
 // BLACKLIST-SRC: ![[EXTRA_GLOBAL]] = !{{{.*}} ![[EXTRA_GLOBAL_LOC:[0-9]+]], !"extra_global", i1 false, i1 false}
 // BLACKLIST-SRC: ![[EXTRA_GLOBAL_LOC]] = !{!"{{.*}}extra-source.cpp", i32 1, i32 5}
 // BLACKLIST-SRC: ![[GLOBAL]] = !{{{.*}} null, null, i1 false, i1 true}
 // BLACKLIST-SRC: ![[DYN_INIT_GLOBAL]] = !{{{.*}} null, null, i1 true, i1 true}
 // BLACKLIST-SRC: ![[ATTR_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
+// BLACKLIST-SRC: ![[DISABLE_INSTR_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
 // BLACKLIST-SRC: ![[BLACKLISTED_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
 // BLACKLIST-SRC: ![[SECTIONED_GLOBAL]] = !{{{.*}} null, null, i1 false, i1 true}
 // BLACKLIST-SRC: ![[SPECIAL_GLOBAL]] = !{{{.*}} null, null, i1 false, i1 true}
Index: clang/test/CodeGen/address-safety-attr-flavors.cpp
==

[PATCH] D114424: [Diagnostic] Clarify -Winfinite-recursion message

2021-11-23 Thread Hirochika Matsumoto via Phabricator via cfe-commits
hkmatsumoto created this revision.
hkmatsumoto 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/D114424

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/test/SemaCXX/warn-infinite-recursion.cpp

Index: clang/test/SemaCXX/warn-infinite-recursion.cpp
===
--- clang/test/SemaCXX/warn-infinite-recursion.cpp
+++ clang/test/SemaCXX/warn-infinite-recursion.cpp
@@ -1,10 +1,10 @@
 // RUN: %clang_cc1 %s -fsyntax-only -verify -Winfinite-recursion
 
-void a() {  // expected-warning{{call itself}}
+void a() {  // expected-warning{{to understand recursion}}
   a();
 }
 
-void b(int x) {  // expected-warning{{call itself}}
+void b(int x) {  // expected-warning{{to understand recursion}}
   if (x)
 b(x);
   else
@@ -16,7 +16,7 @@
 c(5);
 }
 
-void d(int x) {  // expected-warning{{call itself}}
+void d(int x) {  // expected-warning{{to understand recursion}}
   if (x)
 ++x;
   return d(x);
@@ -29,7 +29,7 @@
 void e() { f(); }
 void f() { e(); }
 
-void g() {  // expected-warning{{call itself}}
+void g() {  // expected-warning{{to understand recursion}}
   while (true)
 g();
 
@@ -42,14 +42,14 @@
   }
 }
 
-void i(int x) {  // expected-warning{{call itself}}
+void i(int x) {  // expected-warning{{to understand recursion}}
   while (x < 5) {
 --x;
   }
   i(0);
 }
 
-int j() {  // expected-warning{{call itself}}
+int j() {  // expected-warning{{to understand recursion}}
   return 5 + j();
 }
 
@@ -80,11 +80,11 @@
   void b();
 };
 
-void S::a() {  // expected-warning{{call itself}}
+void S::a() {  // expected-warning{{to understand recursion}}
   return a();
 }
 
-void S::b() {  // expected-warning{{call itself}}
+void S::b() {  // expected-warning{{to understand recursion}}
   int i = 0;
   do {
 ++i;
@@ -95,8 +95,8 @@
 template
 struct T {
   member m;
-  void a() { return a(); }  // expected-warning{{call itself}}
-  static void b() { return b(); }  // expected-warning{{call itself}}
+  void a() { return a(); }  // expected-warning{{to understand recursion}}
+  static void b() { return b(); }  // expected-warning{{to understand recursion}}
 };
 
 void test_T() {
@@ -107,13 +107,13 @@
 
 class U {
   U* u;
-  void Fun() {  // expected-warning{{call itself}}
+  void Fun() {  // expected-warning{{to understand recursion}}
 u->Fun();
   }
 };
 
 // No warnings on templated functions
-// sum<0>() is instantiated, does recursively call itself, but never runs.
+// sum<0>() is instantiated, does recursively to understand recursion, but never runs.
 template 
 int sum() {
   return value + sum();
@@ -157,7 +157,7 @@
   return 0;
 return Wrapper::run();
   }
-  static int run2() {  // expected-warning{{call itself}}
+  static int run2() {  // expected-warning{{to understand recursion}}
 return run2();
   }
 };
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -60,7 +60,7 @@
   "remove call to max function and unsigned zero argument">;
 
 def warn_infinite_recursive_function : Warning<
-  "all paths through this function will call itself">,
+  "in order to understand recursion, you must first understand recursion">,
   InGroup, DefaultIgnore;
 
 def warn_comma_operator : Warning<"possible misuse of comma operator here">,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D114425: [clang] Add __builtin_bswap128

2021-11-23 Thread Nikolas Klauser via Phabricator via cfe-commits
philnik created this revision.
philnik requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

GCC has a `__builtin_bswap128` which is used for `std::byteswap()`. Clang 
should also add this builtin.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114425

Files:
  clang/include/clang/Basic/Builtins.def
  clang/lib/AST/ExprConstant.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/builtins.cpp


Index: clang/test/CodeGen/builtins.cpp
===
--- clang/test/CodeGen/builtins.cpp
+++ clang/test/CodeGen/builtins.cpp
@@ -20,6 +20,10 @@
 decltype(__builtin_bswap32(0)) bswap32 = 42;
 extern uint64_t bswap64;
 decltype(__builtin_bswap64(0)) bswap64 = 42;
+#ifdef __SIZEOF_INT128__
+extern __uint128_t bswap128;
+decltype(__builtin_bswap128(0)) bswap128 = 42;
+#endif
 
 #ifdef __clang__
 extern uint8_t bitrev8;
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -2905,7 +2905,8 @@
   }
   case Builtin::BI__builtin_bswap16:
   case Builtin::BI__builtin_bswap32:
-  case Builtin::BI__builtin_bswap64: {
+  case Builtin::BI__builtin_bswap64:
+  case Builtin::BI__builtin_bswap128: {
 return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::bswap));
   }
   case Builtin::BI__builtin_bitreverse8:
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -11640,7 +11640,8 @@
 
   case Builtin::BI__builtin_bswap16:
   case Builtin::BI__builtin_bswap32:
-  case Builtin::BI__builtin_bswap64: {
+  case Builtin::BI__builtin_bswap64:
+  case Builtin::BI__builtin_bswap128: {
 APSInt Val;
 if (!EvaluateInteger(E->getArg(0), Val, Info))
   return false;
Index: clang/include/clang/Basic/Builtins.def
===
--- clang/include/clang/Basic/Builtins.def
+++ clang/include/clang/Basic/Builtins.def
@@ -512,6 +512,7 @@
 BUILTIN(__builtin_bswap16, "UsUs", "nc")
 BUILTIN(__builtin_bswap32, "UZiUZi", "nc")
 BUILTIN(__builtin_bswap64, "UWiUWi", "nc")
+BUILTIN(__builtin_bswap128, "ULLLiULLLi", "nc")
 
 BUILTIN(__builtin_bitreverse8, "UcUc", "nc")
 BUILTIN(__builtin_bitreverse16, "UsUs", "nc")


Index: clang/test/CodeGen/builtins.cpp
===
--- clang/test/CodeGen/builtins.cpp
+++ clang/test/CodeGen/builtins.cpp
@@ -20,6 +20,10 @@
 decltype(__builtin_bswap32(0)) bswap32 = 42;
 extern uint64_t bswap64;
 decltype(__builtin_bswap64(0)) bswap64 = 42;
+#ifdef __SIZEOF_INT128__
+extern __uint128_t bswap128;
+decltype(__builtin_bswap128(0)) bswap128 = 42;
+#endif
 
 #ifdef __clang__
 extern uint8_t bitrev8;
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -2905,7 +2905,8 @@
   }
   case Builtin::BI__builtin_bswap16:
   case Builtin::BI__builtin_bswap32:
-  case Builtin::BI__builtin_bswap64: {
+  case Builtin::BI__builtin_bswap64:
+  case Builtin::BI__builtin_bswap128: {
 return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::bswap));
   }
   case Builtin::BI__builtin_bitreverse8:
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -11640,7 +11640,8 @@
 
   case Builtin::BI__builtin_bswap16:
   case Builtin::BI__builtin_bswap32:
-  case Builtin::BI__builtin_bswap64: {
+  case Builtin::BI__builtin_bswap64:
+  case Builtin::BI__builtin_bswap128: {
 APSInt Val;
 if (!EvaluateInteger(E->getArg(0), Val, Info))
   return false;
Index: clang/include/clang/Basic/Builtins.def
===
--- clang/include/clang/Basic/Builtins.def
+++ clang/include/clang/Basic/Builtins.def
@@ -512,6 +512,7 @@
 BUILTIN(__builtin_bswap16, "UsUs", "nc")
 BUILTIN(__builtin_bswap32, "UZiUZi", "nc")
 BUILTIN(__builtin_bswap64, "UWiUWi", "nc")
+BUILTIN(__builtin_bswap128, "ULLLiULLLi", "nc")
 
 BUILTIN(__builtin_bitreverse8, "UcUc", "nc")
 BUILTIN(__builtin_bitreverse16, "UsUs", "nc")
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D114370: [clangd] IncludeCleaner: Attribute symbols from non self-contained headers to their parents

2021-11-23 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 389131.
kbobyrev marked 5 inline comments as done.
kbobyrev added a comment.

Address review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114370

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -281,7 +281,8 @@
   auto &SM = AST.getSourceManager();
   auto &Includes = AST.getIncludeStructure();
 
-  auto ReferencedFiles = findReferencedFiles(findReferencedLocations(AST), SM);
+  auto ReferencedFiles =
+  findReferencedFiles(findReferencedLocations(AST), AST.getPreprocessor());
   llvm::StringSet<> ReferencedFileNames;
   for (FileID FID : ReferencedFiles)
 ReferencedFileNames.insert(
@@ -303,6 +304,52 @@
   EXPECT_THAT(getUnused(AST, ReferencedHeaders), ::testing::IsEmpty());
 }
 
+TEST(IncludeCleaner, NonSelfContainedHeaders) {
+  TestTU TU;
+  TU.Code = R"cpp(
+#include "bar.h"
+#include "foo.h"
+
+int LocalFoo = foo::Variable,
+LocalBar = bar::Variable;
+)cpp";
+  TU.AdditionalFiles["bar.h"] = R"cpp(
+#pragma once
+namespace bar {
+#include "indirection.h"
+}
+)cpp";
+  TU.AdditionalFiles["foo.h"] = R"cpp(
+#pragma once
+namespace foo {
+#include "unguarded.h"
+}
+)cpp";
+  TU.AdditionalFiles["indirection.h"] = R"cpp(
+#include "unguarded.h"
+)cpp";
+  TU.AdditionalFiles["unguarded.h"] = R"cpp(
+constexpr int Variable = 42;
+)cpp";
+
+  ParsedAST AST = TU.build();
+
+  auto ReferencedFiles =
+  findReferencedFiles(findReferencedLocations(AST), AST.getPreprocessor());
+  llvm::StringSet<> ReferencedFileNames;
+  auto &SM = AST.getSourceManager();
+  for (FileID FID : ReferencedFiles)
+ReferencedFileNames.insert(
+SM.getPresumedLoc(SM.getLocForStartOfFile(FID)).getFilename());
+  // Note that we have uplifted the referenced files from non self-contained
+  // headers to header-guarded ones.
+  for (const auto &Key : ReferencedFileNames.keys()) {
+llvm::outs() << "Key: " << Key << '\n';
+  }
+  EXPECT_THAT(ReferencedFileNames.keys(),
+  UnorderedElementsAre(testPath("bar.h"), testPath("foo.h")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -266,7 +266,7 @@
 return toURI(Canonical);
   }
 }
-if (!isSelfContainedHeader(FID, FE)) {
+if (!isSelfContainedHeader(*PP, FID, FE)) {
   // A .inc or .def file is often included into a real header to define
   // symbols (e.g. LLVM tablegen files).
   if (Filename.endswith(".inc") || Filename.endswith(".def"))
@@ -279,20 +279,6 @@
 return toURI(FE);
   }
 
-  bool isSelfContainedHeader(FileID FID, const FileEntry *FE) {
-// FIXME: Should files that have been #import'd be considered
-// self-contained? That's really a property of the includer,
-// not of the file.
-if (!PP->getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE) &&
-!PP->getHeaderSearchInfo().hasFileBeenImported(FE))
-  return false;
-// This pattern indicates that a header can't be used without
-// particular preprocessor state, usually set up by another header.
-if (isDontIncludeMeHeader(SM.getBufferData(FID)))
-  return false;
-return true;
-  }
-
   // Is Line an #if or #ifdef directive?
   static bool isIf(llvm::StringRef Line) {
 Line = Line.ltrim();
Index: clang-tools-extra/clangd/SourceCode.h
===
--- clang-tools-extra/clangd/SourceCode.h
+++ clang-tools-extra/clangd/SourceCode.h
@@ -324,6 +324,12 @@
 /// Returns true if the given location is in a generated protobuf file.
 bool isProtoFile(SourceLocation Loc, const SourceManager &SourceMgr);
 
+/// Rather expensive check that uses heuristics to figure out whether given
+/// header is self-contained (include guarded, including not rely on
+/// preprocessor state).
+bool isSelfContainedHeader(const Preprocessor &PP, FileID FID,
+   const FileEntry *FE);
+
 } // namespace clangd
 } // namespace clang
 #endif
Index: clang-tools-extra/clangd/SourceCode.cpp
===
--- clang-tools-extra/clangd/SourceCode.cpp
+

[PATCH] D114370: [clangd] IncludeCleaner: Attribute symbols from non self-contained headers to their parents

2021-11-23 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev added a comment.

In D114370#3148143 , @sammccall wrote:

> The ReferencedFiles is designed to make add() as cheap as possible, and do 
> any per-file logic after folding the fileIDs together.
> This keeps that loop tighter and also isolates the complexity of the symbol 
> vs file logic.
> Any reason we can't do that here?

Good point, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114370

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


[PATCH] D114408: Fold a lot of ffixed_x if judgments

2021-11-23 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 requested changes to this revision.
jrtc27 added a comment.
This revision now requires changes to proceed.

This has clearly not been tested whatsoever, it’s totally broken, the 
preprocessor does not work like that


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114408

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


[PATCH] D113917: Add infrastructure to support matcher names.

2021-11-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

The approach looks fine in general, just some nits when reading through the 
patch.




Comment at: clang/include/clang/ASTMatchers/ASTMatchersInternal.h:152
+  }
+MAKE_MATCHER_NAME_FROM_TYPE(TemplateArgument)
+MAKE_MATCHER_NAME_FROM_TYPE(TemplateArgumentLoc)

These are types that are not covered in the above gen .inc files. I wonder is 
there a way to verify this list is complete? 



Comment at: clang/lib/ASTMatchers/ASTMatchersInternal.cpp:120
+  std::vector InnerMatchers)
+  : MatcherName(MatcherName), InnerMatchers(std::move(InnerMatchers)) {}
 

std::move(MatcherName), and elsewhere.



Comment at: clang/lib/ASTMatchers/ASTMatchersInternal.cpp:164
+public:
+  NameMatcherImpl(std::string _MatcherName,
+  IntrusiveRefCntPtr InnerMatcher)

_MatcherName => MatcherName



Comment at: clang/lib/ASTMatchers/ASTMatchersInternal.cpp:306
+  Copy.Implementation =
+  new NameMatcherImpl(MatcherName, std::move(Copy.Implementation));
+  return Copy;

std::move(MatcherName)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113917

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


[clang] e7cb328 - [clang-format] [PR52527] can join * with /* to form an outside of comment error C4138

2021-11-23 Thread via cfe-commits

Author: mydeveloperday
Date: 2021-11-23T10:36:06Z
New Revision: e7cb3283c8032d89e81b3958b0fd73064ed5e839

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

LOG: [clang-format] [PR52527] can join * with /* to form an outside of comment 
error C4138

https://bugs.llvm.org/show_bug.cgi?id=52527

The follow patch ensures there is always a space between * and /* to prevent 
transforming
```
void foo(* /* comment */)(int bar);
```
into
```
void foo(*/* comment */)(int bar);
```

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index f3f63b4cad234..817bda1780de2 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3246,6 +3246,12 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
   };
   if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
 return true; // Never ever merge two identifiers.
+
+  // Leave a space between * and /* to avoid C4138 `comment end` found outside
+  // of comment.
+  if (Left.is(tok::star) && Right.is(tok::comment))
+return true;
+
   if (Style.isCpp()) {
 if (Left.is(tok::kw_operator))
   return Right.is(tok::coloncolon);

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 6507cbefc5a90..8c8d7a465c795 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -9439,6 +9439,13 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyFormat("void f() { &(*I).first; }");
 
   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
+  verifyFormat("f(* /* confusing comment */ foo);");
+  verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
+  verifyFormat("void foo(int * // this is the first paramters\n"
+   " ,\n"
+   " int second);");
+  verifyFormat("double term = a * // first\n"
+   "  b;");
   verifyFormat(
   "int *MyValues = {\n"
   "*A, // Operator detection might be confused by the '{'\n"



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


[PATCH] D114142: [clang-format] [PR52527] can join * with /* to form an outside of comment error C4138

2021-11-23 Thread MyDeveloperDay via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe7cb3283c803: [clang-format] [PR52527] can join * with /* to 
form an outside of comment error… (authored by MyDeveloperDay).

Changed prior to commit:
  https://reviews.llvm.org/D114142?vs=388696&id=389133#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114142

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -9439,6 +9439,13 @@
   verifyFormat("void f() { &(*I).first; }");
 
   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
+  verifyFormat("f(* /* confusing comment */ foo);");
+  verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
+  verifyFormat("void foo(int * // this is the first paramters\n"
+   " ,\n"
+   " int second);");
+  verifyFormat("double term = a * // first\n"
+   "  b;");
   verifyFormat(
   "int *MyValues = {\n"
   "*A, // Operator detection might be confused by the '{'\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3246,6 +3246,12 @@
   };
   if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
 return true; // Never ever merge two identifiers.
+
+  // Leave a space between * and /* to avoid C4138 `comment end` found outside
+  // of comment.
+  if (Left.is(tok::star) && Right.is(tok::comment))
+return true;
+
   if (Style.isCpp()) {
 if (Left.is(tok::kw_operator))
   return Right.is(tok::coloncolon);


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -9439,6 +9439,13 @@
   verifyFormat("void f() { &(*I).first; }");
 
   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
+  verifyFormat("f(* /* confusing comment */ foo);");
+  verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)");
+  verifyFormat("void foo(int * // this is the first paramters\n"
+   " ,\n"
+   " int second);");
+  verifyFormat("double term = a * // first\n"
+   "  b;");
   verifyFormat(
   "int *MyValues = {\n"
   "*A, // Operator detection might be confused by the '{'\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3246,6 +3246,12 @@
   };
   if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
 return true; // Never ever merge two identifiers.
+
+  // Leave a space between * and /* to avoid C4138 `comment end` found outside
+  // of comment.
+  if (Left.is(tok::star) && Right.is(tok::comment))
+return true;
+
   if (Style.isCpp()) {
 if (Left.is(tok::kw_operator))
   return Right.is(tok::coloncolon);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D113251: [analyzer][doc] Add user documenation for taint analysis

2021-11-23 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 389134.
gamesh411 added a comment.

fix indentation warning
make inline code formatting look better


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113251

Files:
  clang/docs/analyzer/checkers.rst
  clang/docs/analyzer/user-docs/TaintAnalysisConfiguration.rst

Index: clang/docs/analyzer/user-docs/TaintAnalysisConfiguration.rst
===
--- clang/docs/analyzer/user-docs/TaintAnalysisConfiguration.rst
+++ clang/docs/analyzer/user-docs/TaintAnalysisConfiguration.rst
@@ -2,15 +2,16 @@
 Taint Analysis Configuration
 
 
-Clang Static Analyzer uses taint analysis to detect security-related issues in code.
-The backbone of taint analysis in Clang is the `GenericTaintChecker`, which the user can access via the :ref:`alpha-security-taint-TaintPropagation` checker alias and this checker has a default taint-related configuration.
-The checker also provides a configuration interface for extending the default settings by providing a configuration file in `YAML `_ format.
+The Clang Static Analyzer uses taint analysis to detect security-related issues in code.
+The backbone of taint analysis in the Clang SA is the `GenericTaintChecker`, which the user can access via the :ref:`alpha-security-taint-TaintPropagation` checker alias and this checker has a default taint-related configuration.
+The built-in default settings are defined in code, and they are always in effect once the checker is enabled, either directly or via the alias.
+The checker also provides a configuration interface for extending the default settings by providing a configuration file in `YAML `_ format.
 This documentation describes the syntax of the configuration file and gives the informal semantics of the configuration options.
 
 .. contents::
:local:
 
-.. _taint-configuration-overview
+.. _clangsa-taint-configuration-overview:
 
 Overview
 
@@ -18,61 +19,74 @@
 Taint analysis works by checking for the occurrence of special operations during the symbolic execution of the program.
 Taint analysis defines sources, sinks, and propagation rules. It identifies errors by detecting a flow of information that originates from a taint source, reaches a taint sink, and propagates through the program paths via propagation rules.
 A source, sink, or an operation that propagates taint is mainly domain-specific knowledge, but there are some built-in defaults provided by :ref:`alpha-security-taint-TaintPropagation`.
+It is possible to express that a statement sanitizes tainted values by providing a ``Filters`` section in the external configuration (see :ref:`clangsa-taint-configuration-example` and :ref:`clangsa-taint-filter-details`).
+There are no default filters defined in the built-in settings.
 The checker's documentation also specifies how to provide a custom taint configuration with command-line options.
 
-.. _taint-configuration-example:
+.. _clangsa-taint-configuration-example:
 
 Example configuration file
 __
 
 .. code-block:: yaml
 
+  # The entries that specify arguments use 0-based indexing when specifying
+  # input arguments, and -1 is used to denote the return value.
+
   Filters:
-# signature:
-# void cleanse_first_arg(int* arg)
+# Filter functions
+# Taint is sanitized when tainted variables are pass arguments to filters.
+
+# Filter function
+#   void cleanse_first_arg(int* arg)
 #
-# example:
-# int x; // x is tainted
-# cleanse_first_arg(&x); // x is not tainted anymore
+# Result example:
+#   int x; // x is tainted
+#   cleanse_first_arg(&x); // x is not tainted after the call
 - Name: cleanse_first_arg
   Args: [0]
 
   Propagations:
-  # sources:
-  # The omission of SrcArgs key indicates unconditional taint propagation,
-  # which is conceptually what a source does.
-# signature:
-# size_t fread(void *ptr, size_t size, size_t nmemb, FILE * stream)
+# Source functions
+# The omission of SrcArgs key indicates unconditional taint propagation,
+# which is conceptually what a source does.
+
+# Source function
+#   size_t fread(void *ptr, size_t size, size_t nmemb, FILE * stream)
 #
-# example:
-# FILE* f = fopen("file.txt");
-# char buf[1024];
-# size_t read = fread(buf, sizeof(buf[0]), sizeof(buf)/sizeof(buf[0]), f);
-# // both read and buf are tainted
+# Result example:
+#   FILE* f = fopen("file.txt");
+#   char buf[1024];
+#   size_t read = fread(buf, sizeof(buf[0]), sizeof(buf)/sizeof(buf[0]), f);
+#   // both read and buf are tainted
 - Name: fread
   DstArgs: [0, -1]
 
-  # propagations:
-  # The presence of SrcArgs key indicates conditional taint propagation,
-  # which is conceptu

[clang] 1cb3cfd - [clang-format] [NFC] build clang-format with -Wall

2021-11-23 Thread via cfe-commits

Author: mydeveloperday
Date: 2021-11-23T10:43:27Z
New Revision: 1cb3cfd932a0f26e5bfc5d944f63239242fa8ec3

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

LOG: [clang-format] [NFC] build clang-format with -Wall

When building clang-format with -Wall on Visual Studio 20119 we see the 
following, prevent this the only -Wall error
```
..FormatTokenLexer.cpp(45) : warning C4868: compiler may not enforce 
left-to-right evaluation order in braced initializer list
```
Reviewed By: HazardyKnusperkeks
Differential Revision: https://reviews.llvm.org/D113844

Added: 


Modified: 
clang/lib/Format/FormatTokenLexer.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index 8075756cca03..972f59ead5d8 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -37,27 +37,40 @@ FormatTokenLexer::FormatTokenLexer(
   getFormattingLangOpts(Style)));
   Lex->SetKeepWhitespaceMode(true);
 
-  for (const std::string &ForEachMacro : Style.ForEachMacros)
-Macros.insert({&IdentTable.get(ForEachMacro), TT_ForEachMacro});
-  for (const std::string &IfMacro : Style.IfMacros)
-Macros.insert({&IdentTable.get(IfMacro), TT_IfMacro});
-  for (const std::string &AttributeMacro : Style.AttributeMacros)
-Macros.insert({&IdentTable.get(AttributeMacro), TT_AttributeMacro});
-  for (const std::string &StatementMacro : Style.StatementMacros)
-Macros.insert({&IdentTable.get(StatementMacro), TT_StatementMacro});
-  for (const std::string &TypenameMacro : Style.TypenameMacros)
-Macros.insert({&IdentTable.get(TypenameMacro), TT_TypenameMacro});
-  for (const std::string &NamespaceMacro : Style.NamespaceMacros)
-Macros.insert({&IdentTable.get(NamespaceMacro), TT_NamespaceMacro});
+  for (const std::string &ForEachMacro : Style.ForEachMacros) {
+auto Identifier = &IdentTable.get(ForEachMacro);
+Macros.insert({Identifier, TT_ForEachMacro});
+  }
+  for (const std::string &IfMacro : Style.IfMacros) {
+auto Identifier = &IdentTable.get(IfMacro);
+Macros.insert({Identifier, TT_IfMacro});
+  }
+  for (const std::string &AttributeMacro : Style.AttributeMacros) {
+auto Identifier = &IdentTable.get(AttributeMacro);
+Macros.insert({Identifier, TT_AttributeMacro});
+  }
+  for (const std::string &StatementMacro : Style.StatementMacros) {
+auto Identifier = &IdentTable.get(StatementMacro);
+Macros.insert({Identifier, TT_StatementMacro});
+  }
+  for (const std::string &TypenameMacro : Style.TypenameMacros) {
+auto Identifier = &IdentTable.get(TypenameMacro);
+Macros.insert({Identifier, TT_TypenameMacro});
+  }
+  for (const std::string &NamespaceMacro : Style.NamespaceMacros) {
+auto Identifier = &IdentTable.get(NamespaceMacro);
+Macros.insert({Identifier, TT_NamespaceMacro});
+  }
   for (const std::string &WhitespaceSensitiveMacro :
Style.WhitespaceSensitiveMacros) {
-Macros.insert(
-{&IdentTable.get(WhitespaceSensitiveMacro), TT_UntouchableMacroFunc});
+auto Identifier = &IdentTable.get(WhitespaceSensitiveMacro);
+Macros.insert({Identifier, TT_UntouchableMacroFunc});
   }
   for (const std::string &StatementAttributeLikeMacro :
-   Style.StatementAttributeLikeMacros)
-Macros.insert({&IdentTable.get(StatementAttributeLikeMacro),
-   TT_StatementAttributeLikeMacro});
+   Style.StatementAttributeLikeMacros) {
+auto Identifier = &IdentTable.get(StatementAttributeLikeMacro);
+Macros.insert({Identifier, TT_StatementAttributeLikeMacro});
+  }
 }
 
 ArrayRef FormatTokenLexer::lex() {



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


[PATCH] D113844: [clang-format] [NFC] build clang-format with -Wall

2021-11-23 Thread MyDeveloperDay via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1cb3cfd932a0: [clang-format] [NFC] build clang-format with 
-Wall (authored by MyDeveloperDay).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113844

Files:
  clang/lib/Format/FormatTokenLexer.cpp


Index: clang/lib/Format/FormatTokenLexer.cpp
===
--- clang/lib/Format/FormatTokenLexer.cpp
+++ clang/lib/Format/FormatTokenLexer.cpp
@@ -37,27 +37,40 @@
   getFormattingLangOpts(Style)));
   Lex->SetKeepWhitespaceMode(true);
 
-  for (const std::string &ForEachMacro : Style.ForEachMacros)
-Macros.insert({&IdentTable.get(ForEachMacro), TT_ForEachMacro});
-  for (const std::string &IfMacro : Style.IfMacros)
-Macros.insert({&IdentTable.get(IfMacro), TT_IfMacro});
-  for (const std::string &AttributeMacro : Style.AttributeMacros)
-Macros.insert({&IdentTable.get(AttributeMacro), TT_AttributeMacro});
-  for (const std::string &StatementMacro : Style.StatementMacros)
-Macros.insert({&IdentTable.get(StatementMacro), TT_StatementMacro});
-  for (const std::string &TypenameMacro : Style.TypenameMacros)
-Macros.insert({&IdentTable.get(TypenameMacro), TT_TypenameMacro});
-  for (const std::string &NamespaceMacro : Style.NamespaceMacros)
-Macros.insert({&IdentTable.get(NamespaceMacro), TT_NamespaceMacro});
+  for (const std::string &ForEachMacro : Style.ForEachMacros) {
+auto Identifier = &IdentTable.get(ForEachMacro);
+Macros.insert({Identifier, TT_ForEachMacro});
+  }
+  for (const std::string &IfMacro : Style.IfMacros) {
+auto Identifier = &IdentTable.get(IfMacro);
+Macros.insert({Identifier, TT_IfMacro});
+  }
+  for (const std::string &AttributeMacro : Style.AttributeMacros) {
+auto Identifier = &IdentTable.get(AttributeMacro);
+Macros.insert({Identifier, TT_AttributeMacro});
+  }
+  for (const std::string &StatementMacro : Style.StatementMacros) {
+auto Identifier = &IdentTable.get(StatementMacro);
+Macros.insert({Identifier, TT_StatementMacro});
+  }
+  for (const std::string &TypenameMacro : Style.TypenameMacros) {
+auto Identifier = &IdentTable.get(TypenameMacro);
+Macros.insert({Identifier, TT_TypenameMacro});
+  }
+  for (const std::string &NamespaceMacro : Style.NamespaceMacros) {
+auto Identifier = &IdentTable.get(NamespaceMacro);
+Macros.insert({Identifier, TT_NamespaceMacro});
+  }
   for (const std::string &WhitespaceSensitiveMacro :
Style.WhitespaceSensitiveMacros) {
-Macros.insert(
-{&IdentTable.get(WhitespaceSensitiveMacro), TT_UntouchableMacroFunc});
+auto Identifier = &IdentTable.get(WhitespaceSensitiveMacro);
+Macros.insert({Identifier, TT_UntouchableMacroFunc});
   }
   for (const std::string &StatementAttributeLikeMacro :
-   Style.StatementAttributeLikeMacros)
-Macros.insert({&IdentTable.get(StatementAttributeLikeMacro),
-   TT_StatementAttributeLikeMacro});
+   Style.StatementAttributeLikeMacros) {
+auto Identifier = &IdentTable.get(StatementAttributeLikeMacro);
+Macros.insert({Identifier, TT_StatementAttributeLikeMacro});
+  }
 }
 
 ArrayRef FormatTokenLexer::lex() {


Index: clang/lib/Format/FormatTokenLexer.cpp
===
--- clang/lib/Format/FormatTokenLexer.cpp
+++ clang/lib/Format/FormatTokenLexer.cpp
@@ -37,27 +37,40 @@
   getFormattingLangOpts(Style)));
   Lex->SetKeepWhitespaceMode(true);
 
-  for (const std::string &ForEachMacro : Style.ForEachMacros)
-Macros.insert({&IdentTable.get(ForEachMacro), TT_ForEachMacro});
-  for (const std::string &IfMacro : Style.IfMacros)
-Macros.insert({&IdentTable.get(IfMacro), TT_IfMacro});
-  for (const std::string &AttributeMacro : Style.AttributeMacros)
-Macros.insert({&IdentTable.get(AttributeMacro), TT_AttributeMacro});
-  for (const std::string &StatementMacro : Style.StatementMacros)
-Macros.insert({&IdentTable.get(StatementMacro), TT_StatementMacro});
-  for (const std::string &TypenameMacro : Style.TypenameMacros)
-Macros.insert({&IdentTable.get(TypenameMacro), TT_TypenameMacro});
-  for (const std::string &NamespaceMacro : Style.NamespaceMacros)
-Macros.insert({&IdentTable.get(NamespaceMacro), TT_NamespaceMacro});
+  for (const std::string &ForEachMacro : Style.ForEachMacros) {
+auto Identifier = &IdentTable.get(ForEachMacro);
+Macros.insert({Identifier, TT_ForEachMacro});
+  }
+  for (const std::string &IfMacro : Style.IfMacros) {
+auto Identifier = &IdentTable.get(IfMacro);
+Macros.insert({Identifier, TT_IfMacro});
+  }
+  for (const std::string &AttributeMacro : Style.AttributeMacros) {
+auto Identifier = &IdentTable.get(AttributeMacro);
+Macros.insert({Identifier, TT_AttributeMacro});
+  }
+  for (const std::string &StatementMa

[PATCH] D114151: [clang-format] [C++20] [Module] clang-format couldn't recognize partitions

2021-11-23 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 389139.
MyDeveloperDay added a comment.

Fix infinite loop


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

https://reviews.llvm.org/D114151

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Format/FormatToken.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/lib/Format/UnwrappedLineParser.h
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -22597,6 +22597,67 @@
   verifyFormat("auto(*p)() = f;");   // actually a declaration; TODO FIXME
 }
 
+TEST_F(FormatTest, Cpp20ModulesSupport) {
+  FormatStyle Style = getLLVMStyle();
+  Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
+  Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
+
+  verifyFormat("export import foo;", Style);
+  verifyFormat("export import foo:bar;", Style);
+  verifyFormat("export import foo.bar;", Style);
+  verifyFormat("export import foo.bar:baz;", Style);
+  verifyFormat("export import :bar;", Style);
+  verifyFormat("export module foo:bar;", Style);
+  verifyFormat("export module foo;", Style);
+  verifyFormat("export module foo.bar;", Style);
+  verifyFormat("export module foo.bar:baz;", Style);
+  verifyFormat("export import ;", Style);
+
+  verifyFormat("export type_name var;", Style);
+  verifyFormat("template  export using A = B;", Style);
+  verifyFormat("export using A = B;", Style);
+  verifyFormat("export int func() {\n"
+   "  foo();\n"
+   "}",
+   Style);
+  verifyFormat("export struct {\n"
+   "  int foo;\n"
+   "};",
+   Style);
+  verifyFormat("export {\n"
+   "  int foo;\n"
+   "};",
+   Style);
+  verifyFormat("export export char const *hello() { return \"hello\"; }");
+
+  verifyFormat("import bar;", Style);
+  verifyFormat("import foo.bar;", Style);
+  verifyFormat("import foo:bar;", Style);
+  verifyFormat("import :bar;", Style);
+  verifyFormat("import ;", Style);
+  verifyFormat("import \"header\";", Style);
+
+  verifyFormat("module foo;", Style);
+  verifyFormat("module foo:bar;", Style);
+  verifyFormat("module foo.bar;", Style);
+  verifyFormat("module;", Style);
+
+  verifyFormat("export namespace hi {\n"
+   "const char *sayhi();\n"
+   "}",
+   Style);
+
+  verifyFormat("module :private;", Style);
+  verifyFormat("import ;", Style);
+  verifyFormat("import foo...bar;", Style);
+  verifyFormat("import ..;", Style);
+  verifyFormat("module foo:private;", Style);
+  verifyFormat("import a", Style);
+  verifyFormat("module a", Style);
+  verifyFormat("export import a", Style);
+  verifyFormat("export module a", Style);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/UnwrappedLineParser.h
===
--- clang/lib/Format/UnwrappedLineParser.h
+++ clang/lib/Format/UnwrappedLineParser.h
@@ -110,6 +110,7 @@
   void parseCaseLabel();
   void parseSwitch();
   void parseNamespace();
+  void parseModuleImport();
   void parseNew();
   void parseAccessSpecifier();
   bool parseEnum();
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1052,6 +1052,36 @@
   return Tok->Previous && Tok->Previous->isOneOf(tok::l_paren, tok::comma);
 }
 
+void UnwrappedLineParser::parseModuleImport() {
+  nextToken();
+  do {
+if (FormatTok->is(tok::colon)) {
+  FormatTok->setType(TT_ModulePartitionColon);
+}
+// Handle import  as we would an include statement
+else if (FormatTok->is(tok::less)) {
+  nextToken();
+  while (FormatTok && FormatTok->isNot(tok::semi) &&
+ FormatTok->isNot(tok::greater)) {
+// Mark tokens up to the trailing line comments as implicit string
+// literals.
+if (FormatTok->isNot(tok::comment) &&
+!FormatTok->TokenText.startswith("//"))
+  FormatTok->setType(TT_ImplicitStringLiteral);
+nextToken();
+  }
+}
+if (FormatTok->is(tok::semi)) {
+  nextToken();
+  break;
+}
+nextToken();
+  } while (!eof());
+
+  addUnwrappedLine();
+  return;
+}
+
 // readTokenWithJavaScriptASI reads the next token and terminates the current
 // line if JavaScript Automatic Semicolon Insertion must
 // happen between the current token and the next token.
@@ -1250,6 +1280,10 @@
 addUnwrappedLine();
 return;
   }
+  if (Style.isCpp()) {
+parseModuleImport();
+return;
+  }
 }
 if (Style.isCpp() &&
 FormatTok->isOneOf(Keywords.kw_signals, Keywor

[PATCH] D114421: [asan] Add support for disable_sanitizer_instrumentation attribute

2021-11-23 Thread Marco Elver via Phabricator via cfe-commits
melver accepted this revision.
melver added a comment.
This revision is now accepted and ready to land.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114421

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


[PATCH] D114370: [clangd] IncludeCleaner: Attribute symbols from non self-contained headers to their parents

2021-11-23 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:252
   }
-  return std::move(Result.Files);
+  // Post-filtering attributes the locations from non self-contained headers to
+  // their parents while the information about respective SourceLocations and

This comment seems a bit unclear:
 - what the problem is you're solving
 - whether you're describing the behavior you *want* rather than the behavior 
you're trying to avoid.
 - which part of this is "filtering"
 - what the "later" option is you're contrasting to

Maybe something like:

```
// If a header is not self-contained, we consider its symbols a logical part of 
the including file.
// Therefore, mark the parents of all used non-self-contained FileIDs as used.
// Perform this on FileIDs rather than HeaderIDs, as each inclusion of a 
non-self-contained file is distinct.
```



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:262
+ ID != SM.getMainFileID() && FE &&
+ !isSelfContainedHeader(PP, ID, FE);) {
+  ID = SM.getFileID(SM.getIncludeLoc(ID));

it seems like we'd be better off storing the "is-self-contained" in the 
IncludeStructure and looking up the HeaderID here rather than asking the 
preprocessor. That way we rely on info that's better obtained at preamble build 
time.



Comment at: clang-tools-extra/clangd/SourceCode.h:330
+/// preprocessor state).
+bool isSelfContainedHeader(const Preprocessor &PP, FileID FID,
+   const FileEntry *FE);

This helper checks e.g. for "don't include me", which is going to read source 
code of preamble files - we shouldn't do that, it's too slow and racy to do for 
every file in the preamble.

(It would be nice to handle those cases at some point, if we want to do that we 
need to do it at preamble build time and record the results in the 
IncludeStructure)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114370

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


[PATCH] D114427: [clang-tidy] Warn on functional C-style casts

2021-11-23 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp created this revision.
Herald added a subscriber: xazax.hun.
carlosgalvezp requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

The google-readability-casting check is meant to be on par
with cpplint's readability/casting check, according to the
documentation. However it currently does not diagnose
functional casts, like:

float x = 1.5F;
int y = int(x);

This is detected by cpplint, however, and the guidelines
are clear that such a cast is only allowed when the type
is a class type (constructor call):

> You may use cast formats like `T(x)` only when `T` is a class type.

Therefore, update the clang-tidy check to check this
case.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114427

Files:
  clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp
  clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy -std=c++11-or-later %s google-readability-casting %t
+// RUN: %check_clang_tidy -std=c++11-or-later %s google-readability-casting %t -- -- -Wno-c++11-narrowing
 
 bool g() { return false; }
 
@@ -143,11 +143,10 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: redundant cast to the same type
   // CHECK-FIXES: {{^}}  kZero;
 
-  int b2 = int(b);
   int b3 = static_cast(b);
   int b4 = b;
   double aa = a;
-  (void)b2;
+  (void)aa;
   return (void)g();
 }
 
@@ -321,3 +320,17 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: C-style casts are discouraged; use constructor call syntax [
   // CHECK-FIXES: auto s6 = S(cr);
 }
+
+void functional_casts() {
+  float x = 1.5F;
+  auto y = int(x);
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: C-style casts are discouraged; use static_cast
+  // CHECK-FIXES: auto y = static_cast(x);
+
+  // This if fine, compiler won't allow implicit conversions with brace initialization
+  auto z = int{x};
+
+  // Functional casts are allowed if S is of class type
+  const char *str = "foo";
+  auto s = S(str);
+}
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -136,6 +136,8 @@
 - Removed default setting `cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors = "true"`,
   to match the current state of the C++ Core Guidelines.
 
+- Updated `google-readability-casting` to diagnose and fix functional casts, to achieve feature
+  parity with the corresponding `cpplint.py` check.
 
 Removed checks
 ^^
Index: clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.h
===
--- clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.h
+++ clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.h
@@ -34,6 +34,11 @@
   : ClangTidyCheck(Name, Context) {}
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+
+private:
+  template 
+  void checkExpr(const ast_matchers::MatchFinder::MatchResult &Result,
+ const CastExprT *CastExpr);
 };
 
 } // namespace readability
Index: clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp
===
--- clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp
+++ clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp
@@ -31,6 +31,11 @@
   unless(isInTemplateInstantiation()))
   .bind("cast"),
   this);
+  Finder->addMatcher(
+  cxxFunctionalCastExpr(unless(hasDescendant(cxxConstructExpr())),
+unless(hasDescendant(initListExpr(
+  .bind("functional_cast"),
+  this);
 }
 
 static bool needsConstCast(QualType SourceType, QualType DestType) {
@@ -57,7 +62,18 @@
 
 void AvoidCStyleCastsCheck::check(const MatchFinder::MatchResult &Result) {
   const auto *CastExpr = Result.Nodes.getNodeAs("cast");
+  const auto *FunctionalCastExpr =
+  Result.Nodes.getNodeAs("functional_cast");
+
+  if (CastExpr)
+checkExpr(Result, CastExpr);
+  else if (FunctionalCastExpr)
+checkExpr(Result, FunctionalCastExpr);
+}
 
+template 
+void AvoidCStyleCastsCheck::checkExpr(const MatchFinder::MatchResult &Result,
+  const CastExprT *CastExpr) {
   // Ignore casts in macros.
   if (CastExpr->getExprLoc().isMacroID())
 return;
@@ -80,8 +96,14 @@
   const QualType SourceTy

[PATCH] D108621: [HIPSPV] Add CUDA->SPIR-V address space mapping

2021-11-23 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia accepted this revision.
Anastasia added a comment.
This revision is now accepted and ready to land.

LGTM! Thanks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D108621

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


[PATCH] D114430: [clang-format] NFC - recent changes caused clang-format to no longer be clang-formatted.

2021-11-23 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay created this revision.
MyDeveloperDay added reviewers: klimek, HazardyKnusperkeks, curdeius, owenpan.
MyDeveloperDay added projects: clang, clang-format.
MyDeveloperDay requested review of this revision.

The following 2 commits caused files in clang-format to no longer be 
clang-formatted.

we would lose our "clean" status 
https://releases.llvm.org/13.0.0/tools/clang/docs/ClangFormattedStatus.html

c2271926a4fc 
  - Make 
clang-format fuzz through Lexing with asserts enabled 
(https://github.com/llvm/llvm-project/commit/c2271926a4fc )

84bf5e328664 
 - Fix 
various problems found by fuzzing. 
(https://github.com/llvm/llvm-project/commit/84bf5e328664)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114430

Files:
  clang/lib/Format/Format.cpp
  clang/lib/Format/SortJavaScriptImports.cpp
  clang/lib/Format/TokenAnalyzer.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/WhitespaceManager.cpp

Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -913,7 +913,8 @@
   Changes[i].StartOfBlockComment->StartOfTokenColumn -
   Changes[i].StartOfTokenColumn;
 }
-if (Shift < 0) continue;
+if (Shift < 0)
+  continue;
 Changes[i].Spaces += Shift;
 if (i + 1 != Changes.size())
   Changes[i + 1].PreviousEndOfTokenColumn += Shift;
@@ -1269,7 +1270,7 @@
   for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
 const Change &C = Changes[i];
 if (i > 0 && Changes[i - 1].OriginalWhitespaceRange.getBegin() ==
- C.OriginalWhitespaceRange.getBegin()) {
+ C.OriginalWhitespaceRange.getBegin()) {
   // Do not generate two replacements for the same location.
   continue;
 }
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2342,16 +2342,15 @@
 if (NextNonCommentLine && CommentLine &&
 NextNonCommentLine->First->NewlinesBefore <= 1 &&
 NextNonCommentLine->First->OriginalColumn ==
-AL->First->OriginalColumn) {
+AL->First->OriginalColumn) {
   // Align comments for preprocessor lines with the # in column 0 if
   // preprocessor lines are not indented. Otherwise, align with the next
   // line.
-  AL->Level =
-  (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
-   (NextNonCommentLine->Type == LT_PreprocessorDirective ||
-NextNonCommentLine->Type == LT_ImportStatement))
-  ? 0
-  : NextNonCommentLine->Level;
+  AL->Level = (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
+   (NextNonCommentLine->Type == LT_PreprocessorDirective ||
+NextNonCommentLine->Type == LT_ImportStatement))
+  ? 0
+  : NextNonCommentLine->Level;
 } else {
   NextNonCommentLine = AL->First->isNot(tok::r_brace) ? AL : nullptr;
 }
Index: clang/lib/Format/TokenAnalyzer.cpp
===
--- clang/lib/Format/TokenAnalyzer.cpp
+++ clang/lib/Format/TokenAnalyzer.cpp
@@ -37,7 +37,7 @@
 
 // FIXME: Instead of printing the diagnostic we should store it and have a
 // better way to return errors through the format APIs.
-class FatalDiagnosticConsumer: public DiagnosticConsumer {
+class FatalDiagnosticConsumer : public DiagnosticConsumer {
 public:
   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
 const Diagnostic &Info) override {
@@ -71,7 +71,8 @@
   }
   // Validate that we can get the buffer data without a fatal error.
   Env->SM.getBufferData(Env->ID);
-  if (Diags.fatalError()) return nullptr;
+  if (Diags.fatalError())
+return nullptr;
   return Env;
 }
 
@@ -80,8 +81,7 @@
  unsigned LastStartColumn)
 : VirtualSM(new SourceManagerForFile(FileName, Code)), SM(VirtualSM->get()),
   ID(VirtualSM->get().getMainFileID()), FirstStartColumn(FirstStartColumn),
-  NextStartColumn(NextStartColumn), LastStartColumn(LastStartColumn) {
-}
+  NextStartColumn(NextStartColumn), LastStartColumn(LastStartColumn) {}
 
 TokenAnalyzer::TokenAnalyzer(const Environment &Env, const FormatStyle &Style)
 : Style(Style), Env(Env),
Index: clang/lib/Format/SortJavaScriptImports.cpp
===
--- clang/lib/Format/SortJavaScriptImports.cpp
+++ clang/lib/Format/SortJavaScriptImports.cpp
@@ -553,9 +553,7 @@
   auto Env = Environment::make(Code, FileName, Ranges);
   if (!Env)
 return {};
-  return JavaScript

[PATCH] D110618: [HIPSPV][2/4] Add HIPSPV tool chain

2021-11-23 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

Could you please clarify the interface to SPIRV-LLVM-Translator tool, 
specifically:

- Does clang lookup the path to the translator or assume any default path?
- Is there any diagnostic provided if the translator not installed/found?
- How does clang synchronize with the translator versions i.e. some LLVM IR 
might not be ingested by certain version of the translator. Would this results 
in the translator ICE or error in the translator, or is it something that can 
be diagnosed early by clang or during clang build/installation?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110618

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


[PATCH] D114427: [clang-tidy] Warn on functional C-style casts

2021-11-23 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp updated this revision to Diff 389157.
carlosgalvezp added a comment.

Fix numbering of variables.


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

https://reviews.llvm.org/D114427

Files:
  clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp
  clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy -std=c++11-or-later %s google-readability-casting %t
+// RUN: %check_clang_tidy -std=c++11-or-later %s google-readability-casting %t -- -- -Wno-c++11-narrowing
 
 bool g() { return false; }
 
@@ -143,11 +143,10 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: redundant cast to the same type
   // CHECK-FIXES: {{^}}  kZero;
 
-  int b2 = int(b);
   int b3 = static_cast(b);
   int b4 = b;
   double aa = a;
-  (void)b2;
+  (void)aa;
   return (void)g();
 }
 
@@ -321,3 +320,17 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: C-style casts are discouraged; use constructor call syntax [
   // CHECK-FIXES: auto s6 = S(cr);
 }
+
+void functional_casts() {
+  float x = 1.5F;
+  auto y = int(x);
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: C-style casts are discouraged; use static_cast
+  // CHECK-FIXES: auto y = static_cast(x);
+
+  // This if fine, compiler won't allow implicit conversions with brace initialization
+  auto z = int{x};
+
+  // Functional casts are allowed if S is of class type
+  const char *str = "foo";
+  auto s = S(str);
+}
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -136,6 +136,8 @@
 - Removed default setting `cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors = "true"`,
   to match the current state of the C++ Core Guidelines.
 
+- Updated `google-readability-casting` to diagnose and fix functional casts, to achieve feature
+  parity with the corresponding `cpplint.py` check.
 
 Removed checks
 ^^
Index: clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.h
===
--- clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.h
+++ clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.h
@@ -34,6 +34,11 @@
   : ClangTidyCheck(Name, Context) {}
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+
+private:
+  template 
+  void checkExpr(const ast_matchers::MatchFinder::MatchResult &Result,
+ const CastExprT *CastExpr);
 };
 
 } // namespace readability
Index: clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp
===
--- clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp
+++ clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp
@@ -31,6 +31,11 @@
   unless(isInTemplateInstantiation()))
   .bind("cast"),
   this);
+  Finder->addMatcher(
+  cxxFunctionalCastExpr(unless(hasDescendant(cxxConstructExpr())),
+unless(hasDescendant(initListExpr(
+  .bind("functional_cast"),
+  this);
 }
 
 static bool needsConstCast(QualType SourceType, QualType DestType) {
@@ -57,7 +62,18 @@
 
 void AvoidCStyleCastsCheck::check(const MatchFinder::MatchResult &Result) {
   const auto *CastExpr = Result.Nodes.getNodeAs("cast");
+  const auto *FunctionalCastExpr =
+  Result.Nodes.getNodeAs("functional_cast");
+
+  if (CastExpr)
+checkExpr(Result, CastExpr);
+  else if (FunctionalCastExpr)
+checkExpr(Result, FunctionalCastExpr);
+}
 
+template 
+void AvoidCStyleCastsCheck::checkExpr(const MatchFinder::MatchResult &Result,
+  const CastExprT *CastExpr) {
   // Ignore casts in macros.
   if (CastExpr->getExprLoc().isMacroID())
 return;
@@ -80,8 +96,14 @@
   const QualType SourceType = SourceTypeAsWritten.getCanonicalType();
   const QualType DestType = DestTypeAsWritten.getCanonicalType();
 
-  auto ReplaceRange = CharSourceRange::getCharRange(
-  CastExpr->getLParenLoc(), CastExpr->getSubExprAsWritten()->getBeginLoc());
+  CharSourceRange ReplaceRange;
+  if (isa(CastExpr))
+ReplaceRange = CharSourceRange::getCharRange(
+CastExpr->getLParenLoc(),
+CastExpr->getSubExprAsWritten()->getBeginLoc());
+  else if (isa(CastExpr))
+ReplaceRange = CharSourceRange::getCharRange(CastExpr->getBeginLoc(),
+   

[PATCH] D114427: [clang-tidy] Warn on functional C-style casts

2021-11-23 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp updated this revision to Diff 389159.
carlosgalvezp added a comment.

Fix numbering in variables.


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

https://reviews.llvm.org/D114427

Files:
  clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp
  clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy -std=c++11-or-later %s google-readability-casting %t
+// RUN: %check_clang_tidy -std=c++11-or-later %s google-readability-casting %t -- -- -Wno-c++11-narrowing
 
 bool g() { return false; }
 
@@ -143,11 +143,10 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: redundant cast to the same type
   // CHECK-FIXES: {{^}}  kZero;
 
-  int b2 = int(b);
-  int b3 = static_cast(b);
-  int b4 = b;
+  int b2 = static_cast(b);
+  int b3 = b;
   double aa = a;
-  (void)b2;
+  (void)aa;
   return (void)g();
 }
 
@@ -321,3 +320,17 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: C-style casts are discouraged; use constructor call syntax [
   // CHECK-FIXES: auto s6 = S(cr);
 }
+
+void functional_casts() {
+  float x = 1.5F;
+  auto y = int(x);
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: C-style casts are discouraged; use static_cast
+  // CHECK-FIXES: auto y = static_cast(x);
+
+  // This if fine, compiler won't allow implicit conversions with brace initialization
+  auto z = int{x};
+
+  // Functional casts are allowed if S is of class type
+  const char *str = "foo";
+  auto s = S(str);
+}
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -136,6 +136,8 @@
 - Removed default setting `cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors = "true"`,
   to match the current state of the C++ Core Guidelines.
 
+- Updated `google-readability-casting` to diagnose and fix functional casts, to achieve feature
+  parity with the corresponding `cpplint.py` check.
 
 Removed checks
 ^^
Index: clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.h
===
--- clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.h
+++ clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.h
@@ -34,6 +34,11 @@
   : ClangTidyCheck(Name, Context) {}
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+
+private:
+  template 
+  void checkExpr(const ast_matchers::MatchFinder::MatchResult &Result,
+ const CastExprT *CastExpr);
 };
 
 } // namespace readability
Index: clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp
===
--- clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp
+++ clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp
@@ -31,6 +31,11 @@
   unless(isInTemplateInstantiation()))
   .bind("cast"),
   this);
+  Finder->addMatcher(
+  cxxFunctionalCastExpr(unless(hasDescendant(cxxConstructExpr())),
+unless(hasDescendant(initListExpr(
+  .bind("functional_cast"),
+  this);
 }
 
 static bool needsConstCast(QualType SourceType, QualType DestType) {
@@ -57,7 +62,18 @@
 
 void AvoidCStyleCastsCheck::check(const MatchFinder::MatchResult &Result) {
   const auto *CastExpr = Result.Nodes.getNodeAs("cast");
+  const auto *FunctionalCastExpr =
+  Result.Nodes.getNodeAs("functional_cast");
+
+  if (CastExpr)
+checkExpr(Result, CastExpr);
+  else if (FunctionalCastExpr)
+checkExpr(Result, FunctionalCastExpr);
+}
 
+template 
+void AvoidCStyleCastsCheck::checkExpr(const MatchFinder::MatchResult &Result,
+  const CastExprT *CastExpr) {
   // Ignore casts in macros.
   if (CastExpr->getExprLoc().isMacroID())
 return;
@@ -80,8 +96,14 @@
   const QualType SourceType = SourceTypeAsWritten.getCanonicalType();
   const QualType DestType = DestTypeAsWritten.getCanonicalType();
 
-  auto ReplaceRange = CharSourceRange::getCharRange(
-  CastExpr->getLParenLoc(), CastExpr->getSubExprAsWritten()->getBeginLoc());
+  CharSourceRange ReplaceRange;
+  if (isa(CastExpr))
+ReplaceRange = CharSourceRange::getCharRange(
+CastExpr->getLParenLoc(),
+CastExpr->getSubExprAsWritten()->getBeginLoc());
+  else if (isa(CastExpr))
+ReplaceRange = CharSourceRange::getCharRange(CastExpr->

[PATCH] D114234: [clang][dataflow] Add base types for building dataflow analyses

2021-11-23 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 389166.
sgatev added a comment.

Remove unnecessary constructor.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114234

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Environment.h
  clang/lib/Analysis/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp

Index: clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
@@ -0,0 +1,30 @@
+//===- DataflowAnalysis.cpp ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#include 
+
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Optional.h"
+
+using namespace clang;
+using namespace dataflow;
+
+std::vector>
+runDataflowAnalysis(const CFG &Cfg, DataflowAnalysisDynamic &Analysis,
+const Environment &InitEnv) {
+  // FIXME: Implement work list-based algorithm to compute the fixed
+  // point of `Analysis::transform` for every basic block in `Cfg`.
+  return {};
+}
Index: clang/lib/Analysis/FlowSensitive/CMakeLists.txt
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/CMakeLists.txt
@@ -0,0 +1,7 @@
+add_clang_library(clangAnalysisFlowSensitive
+  DataflowAnalysis.cpp
+
+  LINK_LIBS
+  clangAnalysis
+  clangAST
+  )
Index: clang/lib/Analysis/CMakeLists.txt
===
--- clang/lib/Analysis/CMakeLists.txt
+++ clang/lib/Analysis/CMakeLists.txt
@@ -44,3 +44,4 @@
   )
 
 add_subdirectory(plugins)
+add_subdirectory(FlowSensitive)
Index: clang/include/clang/Analysis/FlowSensitive/Environment.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/Environment.h
@@ -0,0 +1,27 @@
+//===-- Environment.h ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines an Environment class that is used by dataflow analyses
+//  that run over Control-Flow Graphs (CFGs) to keep track of the state of the
+//  program at given program points.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+
+namespace clang {
+namespace dataflow {
+
+/// Holds the state of the program (store and heap) at a given program point.
+class Environment {};
+
+} // namespace dataflow
+} // namespace clang
+
+#endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
Index: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -0,0 +1,160 @@
+//===- DataflowAnalysis.h ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+
+#include 
+#include 
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Any.h"
+#include "llvm/ADT/Optional.h"
+
+namespace clang {
+namespace dataflow {
+
+/// Type-erased lattice element container.
+///
+/// Requirements:
+

[PATCH] D114099: Enable `_Float16` type support on X86 without the avx512fp16 flag

2021-11-23 Thread Sylvestre Ledru via Phabricator via cfe-commits
sylvestre.ledru added a comment.

As mentioned in 
https://github.com/llvm/llvm-project/commit/6623c02d70c3732dbea59c6d79c69501baf9627b#commitcomment-60741407

This change is breaking build of compiler-rt on Ubuntu bionic and others on 
amd64:

  
"/build/llvm-toolchain-snapshot-14~++2029100719+d729f4c38fca/build-llvm/./bin/clang"
 --target=x86_64-pc-linux-gnu -DVISIBILITY_HIDDEN  -fstack-protector-strong 
-Wformat -Werror=format-security -Wno-unused-command-line-argument -Wdate-time 
-D_FORTIFY_SOURCE=2 -O3 -DNDEBUG  -m32 -DCOMPILER_RT_HAS_FLOAT16 -std=c11 -fPIC 
-fno-builtin -fvisibility=hidden -fomit-frame-pointer -MD -MT 
CMakeFiles/clang_rt.builtins-i386.dir/extendhfsf2.c.o -MF 
CMakeFiles/clang_rt.builtins-i386.dir/extendhfsf2.c.o.d -o 
CMakeFiles/clang_rt.builtins-i386.dir/extendhfsf2.c.o -c 
'/build/llvm-toolchain-snapshot-14~++2029100719+d729f4c38fca/compiler-rt/lib/builtins/extendhfsf2.c'
  In file included from 
/build/llvm-toolchain-snapshot-14~++2029100719+d729f4c38fca/compiler-rt/lib/builtins/extendhfsf2.c:11:
  In file included from 
/build/llvm-toolchain-snapshot-14~++2029100719+d729f4c38fca/compiler-rt/lib/builtins/fp_extend_impl.inc:38:
  
/build/llvm-toolchain-snapshot-14~++2029100719+d729f4c38fca/compiler-rt/lib/builtins/fp_extend.h:44:9:
 error: _Float16 is not supported on this target
  typedef _Float16 src_t;
  ^
  1 error generated.


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

https://reviews.llvm.org/D114099

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


[PATCH] D114099: Enable `_Float16` type support on X86 without the avx512fp16 flag

2021-11-23 Thread Sylvestre Ledru via Phabricator via cfe-commits
sylvestre.ledru added a comment.

Full log:
https://llvm-jenkins.debian.net/view/Debian%20sid/job/llvm-toolchain-binaries/architecture=amd64,distribution=unstable,label=amd64/104/consoleFull


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

https://reviews.llvm.org/D114099

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


[PATCH] D114099: Enable `_Float16` type support on X86 without the avx512fp16 flag

2021-11-23 Thread Sylvestre Ledru via Phabricator via cfe-commits
sylvestre.ledru added a comment.

Actually, it breaks on all Debian.
Could you please revert it?


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

https://reviews.llvm.org/D114099

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


[clang] fd759d4 - Revert "The _Float16 type is supported on x86 systems with SSE2 enabled."

2021-11-23 Thread Zahira Ammarguellat via cfe-commits

Author: Zahira Ammarguellat
Date: 2021-11-23T08:00:57-05:00
New Revision: fd759d42c9f84d16efa99a59620cbb3e6836fed4

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

LOG: Revert "The _Float16 type is supported on x86 systems with SSE2 enabled."

This reverts commit 6623c02d70c3732dbea59c6d79c69501baf9627b.
The change seems to be breaking build of compiler-rt on Debian.

Added: 
clang/test/CodeGen/X86/avx512fp16-abi.c
clang/test/CodeGen/X86/avx512fp16-complex.c

Modified: 
clang/docs/LanguageExtensions.rst
clang/docs/ReleaseNotes.rst
clang/lib/Basic/Targets/X86.cpp
clang/test/Sema/Float16.c
clang/test/Sema/conversion-target-dep.c
clang/test/SemaCXX/Float16.cpp

Removed: 
clang/test/CodeGen/X86/Float16-arithmetic.c
clang/test/CodeGen/X86/fp16-abi.c
clang/test/CodeGen/X86/fp16-complex.c



diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index dfdb01b8ff542..60b1ed383a1ff 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -673,7 +673,7 @@ targets pending ABI standardization:
 * 64-bit ARM (AArch64)
 * AMDGPU
 * SPIR
-* X86 (Available with feature SSE2 and up enabled)
+* X86 (Only available under feature AVX512-FP16)
 
 ``_Float16`` will be supported on more targets as they define ABIs for it.
 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d2fa7ff05a160..104d2e908d809 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -187,7 +187,6 @@ X86 Support in Clang
 
 
 - Support for ``AVX512-FP16`` instructions has been added.
-- Support for ``_Float16`` type has been added.
 
 Arm and AArch64 Support in Clang
 

diff  --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index 5e36868937194..454a7743dded3 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -239,9 +239,9 @@ bool 
X86TargetInfo::handleTargetFeatures(std::vector &Features,
   HasAVX512ER = true;
 } else if (Feature == "+avx512fp16") {
   HasAVX512FP16 = true;
+  HasFloat16 = true;
 } else if (Feature == "+avx512pf") {
   HasAVX512PF = true;
-  HasLegalHalfType = true;
 } else if (Feature == "+avx512dq") {
   HasAVX512DQ = true;
 } else if (Feature == "+avx512bitalg") {
@@ -369,8 +369,6 @@ bool 
X86TargetInfo::handleTargetFeatures(std::vector &Features,
  .Default(NoXOP);
 XOPLevel = std::max(XOPLevel, XLevel);
   }
-  // Turn on _float16 for x86 (feature sse2)
-  HasFloat16 = SSELevel >= SSE2;
 
   // LLVM doesn't have a separate switch for fpmath, so only accept it if it
   // matches the selected sse level.

diff  --git a/clang/test/CodeGen/X86/Float16-arithmetic.c 
b/clang/test/CodeGen/X86/Float16-arithmetic.c
deleted file mode 100644
index 7f7b3ff594424..0
--- a/clang/test/CodeGen/X86/Float16-arithmetic.c
+++ /dev/null
@@ -1,73 +0,0 @@
-// RUN: %clang_cc1 -triple  x86_64-unknown-unknown -emit-llvm  \
-// RUN: < %s  | FileCheck %s --check-prefixes=CHECK
-
-_Float16 add1(_Float16 a, _Float16 b) {
-  // CHECK-LABEL: define{{.*}} half @add1
-  // CHECK: alloca half
-  // CHECK: alloca half
-  // CHECK: store half {{.*}}, half*
-  // CHECK: store half {{.*}}, half*
-  // CHECK: load half, half*
-  // CHECK: load half, half* {{.*}}
-  // CHECK: fadd half {{.*}}, {{.*}}
-  // CHECK: ret half
-  return a + b;
-}
-
-_Float16 add2(_Float16 a, _Float16 b, _Float16 c) {
-  // CHECK-LABEL: define{{.*}} half @add2
-  // CHECK: alloca half
-  // CHECK: alloca half
-  // CHECK: alloca half
-  // CHECK: store half {{.*}}, half*
-  // CHECK: store half {{.*}}, half*
-  // CHECK: store half {{.*}}, half*
-  // CHECK: load half, half* {{.*}}
-  // CHECK: load half, half* {{.*}}
-  // CHECK: fadd half {{.*}}, {{.*}}
-  // CHECK: load half, half* {{.*}}
-  // CHECK: fadd half {{.*}}, {{.*}}
-  // CHECK: ret half
-return a + b + c;
-}
-
-_Float16 sub(_Float16 a, _Float16 b) {
-  // CHECK-LABEL: define{{.*}} half @sub
-  // CHECK: alloca half
-  // CHECK: alloca half
-  // CHECK: store half {{.*}}, half*
-  // CHECK: store half {{.*}}, half*
-  // CHECK: load half, half*
-  // CHECK: load half, half* {{.*}}
-  // CHECK: fsub half {{.*}}, {{.*}}
-  // CHECK: ret half
-  return a - b;
-}
-
-_Float16 div(_Float16 a, _Float16 b) {
-  // CHECK-LABEL: define{{.*}} half @div
-  // CHECK: alloca half
-  // CHECK: alloca half
-  // CHECK: store half {{.*}}, half*
-  // CHECK: store half {{.*}}, half*
-  // CHECK: load half, half* {{.*}}
-  // CHECK: load half, half* {{.*}}
-  // CHECK: fdiv half {{.*}}, {{.*}}
-  // CHECK: ret half
-  return a / b;
-}
-
-_Float16 mul(_Float16 a, _Float16 b) {
-  // CHECK

[PATCH] D114099: Enable `_Float16` type support on X86 without the avx512fp16 flag

2021-11-23 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added a comment.

In D114099#3148631 , @sylvestre.ledru 
wrote:

> Actually, it breaks on all Debian.
> Could you please revert it?

Done.


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

https://reviews.llvm.org/D114099

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


[PATCH] D110216: [clang] retain type sugar in auto / template argument deduction

2021-11-23 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov added a comment.

In D110216#3139129 , @lkail wrote:

> Hi we found regression in our internal tests. It compiles with clang-13.0.0 
> https://godbolt.org/z/3abGrcf7o and gcc https://godbolt.org/z/K9oj3Grs1, but 
> fails with clang-trunk https://godbolt.org/z/1Tehxa1x9. Is it an intended 
> change? If so, do we have to document this?

Thanks for the report!

No it was not intended change, this patch should not affect partial ordering 
like that, modulo any bugs we might have accidentally fixed.
What happened here is that we lost a very small piece of code in the 
refactoring, which was introduced more than 10 years ago, but had no test 
coverage.
You just provided it though, and I am working on a patch to restore it shortly.

In D110216#3140678 , @thakis wrote:

> Haha :) Thanks for taking a look. aka for typedefs sounds like a nice 
> approach to me.

Thanks, low on bandwidth right now but I will get to it :-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110216

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


[PATCH] D110216: [clang] retain type sugar in auto / template argument deduction

2021-11-23 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov added a comment.

Fix pushed to https://reviews.llvm.org/D114207


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110216

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


[PATCH] D113372: [Driver] Add CLANG_DEFAULT_PIE to emulate GCC --enable-default-pie

2021-11-23 Thread Sylvestre Ledru via Phabricator via cfe-commits
sylvestre.ledru added a comment.

Maybe add it to the release notes too?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113372

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


[PATCH] D110663: [Driver] Support Debian multiarch style lib/clang/14.0.0/x86_64-linux-gnu runtime path and include/x86_64-linux-gnu/c++/v1 libc++ path

2021-11-23 Thread Sylvestre Ledru via Phabricator via cfe-commits
sylvestre.ledru added a comment.

I am not sure why you are pinging this review often?! Maybe chat with people 
who gave you feedback before directly?!

Myself I wasted so much time because of D107799 
 that I am very reluctant to enable 
LLVM_ENABLE_PER_TARGET_RUNTIME_DIR again.
The mismatch of the triple / quadruple between the system triple and what have 
been decided in llvm ( x86_64-linux-gnu vs x86_64-pc-linux-gnu)

> Moreover, llvm-project has always had the attitude: "downstream projects are 
> on their own".

I am not sure it is a correct statement. llvm project is a bunch of people with 
different focus. 
But in general, we are trying to be nice with the ecosystem and people who rely 
on this software.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110663

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


[PATCH] D114370: [clangd] IncludeCleaner: Attribute symbols from non self-contained headers to their parents

2021-11-23 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 389183.
kbobyrev marked 2 inline comments as done.
kbobyrev added a comment.

Resolve most comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114370

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -281,7 +281,8 @@
   auto &SM = AST.getSourceManager();
   auto &Includes = AST.getIncludeStructure();
 
-  auto ReferencedFiles = findReferencedFiles(findReferencedLocations(AST), SM);
+  auto ReferencedFiles =
+  findReferencedFiles(findReferencedLocations(AST), AST.getPreprocessor());
   llvm::StringSet<> ReferencedFileNames;
   for (FileID FID : ReferencedFiles)
 ReferencedFileNames.insert(
@@ -303,6 +304,52 @@
   EXPECT_THAT(getUnused(AST, ReferencedHeaders), ::testing::IsEmpty());
 }
 
+TEST(IncludeCleaner, NonSelfContainedHeaders) {
+  TestTU TU;
+  TU.Code = R"cpp(
+#include "bar.h"
+#include "foo.h"
+
+int LocalFoo = foo::Variable,
+LocalBar = bar::Variable;
+)cpp";
+  TU.AdditionalFiles["bar.h"] = R"cpp(
+#pragma once
+namespace bar {
+#include "indirection.h"
+}
+)cpp";
+  TU.AdditionalFiles["foo.h"] = R"cpp(
+#pragma once
+namespace foo {
+#include "unguarded.h"
+}
+)cpp";
+  TU.AdditionalFiles["indirection.h"] = R"cpp(
+#include "unguarded.h"
+)cpp";
+  TU.AdditionalFiles["unguarded.h"] = R"cpp(
+constexpr int Variable = 42;
+)cpp";
+
+  ParsedAST AST = TU.build();
+
+  auto ReferencedFiles =
+  findReferencedFiles(findReferencedLocations(AST), AST.getPreprocessor());
+  llvm::StringSet<> ReferencedFileNames;
+  auto &SM = AST.getSourceManager();
+  for (FileID FID : ReferencedFiles)
+ReferencedFileNames.insert(
+SM.getPresumedLoc(SM.getLocForStartOfFile(FID)).getFilename());
+  // Note that we have uplifted the referenced files from non self-contained
+  // headers to header-guarded ones.
+  for (const auto &Key : ReferencedFileNames.keys()) {
+llvm::outs() << "Key: " << Key << '\n';
+  }
+  EXPECT_THAT(ReferencedFileNames.keys(),
+  UnorderedElementsAre(testPath("bar.h"), testPath("foo.h")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -266,7 +266,7 @@
 return toURI(Canonical);
   }
 }
-if (!isSelfContainedHeader(FID, FE)) {
+if (!isSelfContainedHeader(*PP, FID, FE, /*ExpensiveCheck=*/true)) {
   // A .inc or .def file is often included into a real header to define
   // symbols (e.g. LLVM tablegen files).
   if (Filename.endswith(".inc") || Filename.endswith(".def"))
@@ -279,20 +279,6 @@
 return toURI(FE);
   }
 
-  bool isSelfContainedHeader(FileID FID, const FileEntry *FE) {
-// FIXME: Should files that have been #import'd be considered
-// self-contained? That's really a property of the includer,
-// not of the file.
-if (!PP->getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE) &&
-!PP->getHeaderSearchInfo().hasFileBeenImported(FE))
-  return false;
-// This pattern indicates that a header can't be used without
-// particular preprocessor state, usually set up by another header.
-if (isDontIncludeMeHeader(SM.getBufferData(FID)))
-  return false;
-return true;
-  }
-
   // Is Line an #if or #ifdef directive?
   static bool isIf(llvm::StringRef Line) {
 Line = Line.ltrim();
Index: clang-tools-extra/clangd/SourceCode.h
===
--- clang-tools-extra/clangd/SourceCode.h
+++ clang-tools-extra/clangd/SourceCode.h
@@ -324,6 +324,13 @@
 /// Returns true if the given location is in a generated protobuf file.
 bool isProtoFile(SourceLocation Loc, const SourceManager &SourceMgr);
 
+/// Use heuristics to check whether the header is self-contained (has header
+/// guard, does not rely on preprocessor state).
+/// When \p ExpensiveCheck is true, this will read a portion of the file which
+/// be discouraged in performance-sensitive context.
+bool isSelfContainedHeader(const Preprocessor &PP, FileID FID,
+   const FileEntry *FE, bool ExpensiveCheck = false);
+
 } // namespace clangd
 } // namespace clang
 #endif
Index: clang-tools-

[PATCH] D114370: [clangd] IncludeCleaner: Attribute symbols from non self-contained headers to their parents

2021-11-23 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev added inline comments.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:262
+ ID != SM.getMainFileID() && FE &&
+ !isSelfContainedHeader(PP, ID, FE);) {
+  ID = SM.getFileID(SM.getIncludeLoc(ID));

sammccall wrote:
> it seems like we'd be better off storing the "is-self-contained" in the 
> IncludeStructure and looking up the HeaderID here rather than asking the 
> preprocessor. That way we rely on info that's better obtained at preamble 
> build time.
I am slightly confused: we don't really have the `IncludeStructure` here and it 
is logically detached from the `IncludeStructure` processing. We'd still have 
to unroll the chain of FIDs in here, so the only difference would be querying 
`IncludeStructure` data for the cached `isSelfContainedHeader` value, is that 
right? Why is obtaining that info at preamble build time better?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114370

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


[PATCH] D114249: [clang-tidy] performance-unnecessary-copy-initialization: Fix false negative.

2021-11-23 Thread Clement Courbet via Phabricator via cfe-commits
courbet updated this revision to Diff 389184.
courbet added a comment.

Canonicalize more types and add more container tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114249

Files:
  clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
  
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
@@ -3,11 +3,19 @@
 template 
 struct Iterator {
   void operator++();
-  const T &operator*() const;
+  T &operator*() const;
   bool operator!=(const Iterator &) const;
   typedef const T &const_reference;
 };
 
+template 
+struct ConstIterator {
+  void operator++();
+  const T &operator*() const;
+  bool operator!=(const ConstIterator &) const;
+  typedef const T &const_reference;
+};
+
 struct ExpensiveToCopyType {
   ExpensiveToCopyType();
   virtual ~ExpensiveToCopyType();
@@ -15,8 +23,6 @@
   using ConstRef = const ExpensiveToCopyType &;
   ConstRef referenceWithAlias() const;
   const ExpensiveToCopyType *pointer() const;
-  Iterator begin() const;
-  Iterator end() const;
   void nonConstMethod();
   bool constMethod() const;
   template 
@@ -24,6 +30,21 @@
   operator int() const; // Implicit conversion to int.
 };
 
+template 
+struct Container {
+  bool empty() const;
+  const T& operator[](int) const;
+  const T& operator[](int);
+  Iterator begin();
+  Iterator end();
+  ConstIterator begin() const;
+  ConstIterator end() const;
+  void nonConstMethod();
+  bool constMethod() const;
+};
+
+using ExpensiveToCopyContainerAlias = Container;
+
 struct TrivialToCopyType {
   const TrivialToCopyType &reference() const;
 };
@@ -138,6 +159,94 @@
   VarCopyConstructed.constMethod();
 }
 
+void PositiveOperatorCallConstReferenceParam(const Container &C) {
+  const auto AutoAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 'AutoAssigned'
+  // CHECK-FIXES: const auto& AutoAssigned = C[42];
+  AutoAssigned.constMethod();
+
+  const auto AutoCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 'AutoCopyConstructed'
+  // CHECK-FIXES: const auto& AutoCopyConstructed(C[42]);
+  AutoCopyConstructed.constMethod();
+
+  const ExpensiveToCopyType VarAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 'VarAssigned'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarAssigned = C[42];
+  VarAssigned.constMethod();
+
+  const ExpensiveToCopyType VarCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 'VarCopyConstructed'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarCopyConstructed(C[42]);
+  VarCopyConstructed.constMethod();
+}
+
+void PositiveOperatorCallConstValueParam(const Container C) {
+  const auto AutoAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 'AutoAssigned'
+  // CHECK-FIXES: const auto& AutoAssigned = C[42];
+  AutoAssigned.constMethod();
+
+  const auto AutoCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 'AutoCopyConstructed'
+  // CHECK-FIXES: const auto& AutoCopyConstructed(C[42]);
+  AutoCopyConstructed.constMethod();
+
+  const ExpensiveToCopyType VarAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 'VarAssigned'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarAssigned = C[42];
+  VarAssigned.constMethod();
+
+  const ExpensiveToCopyType VarCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 'VarCopyConstructed'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarCopyConstructed(C[42]);
+  VarCopyConstructed.constMethod();
+}
+
+void PositiveOperatorCallConstValueParamAlias(const ExpensiveToCopyContainerAlias C) {
+  const auto AutoAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 'AutoAssigned'
+  // CHECK-FIXES: const auto& AutoAssigned = C[42];
+  AutoAssigned.constMethod();
+
+  const auto AutoCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 'AutoCopyConstructed'
+  // CHECK-FIXES: const auto& AutoCopyConstructed(C[42]);
+  AutoCopyConstructed.constMethod();
+
+  const ExpensiveToCopyType VarAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 'VarAssigned'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarAssigned = C[42];
+  VarAssigned.constMethod();
+
+  const ExpensiveToCopyType VarCopyConstructed(C[42])

[PATCH] D113753: [Analyzer][Core] Better simplification in SimpleSValBuilder::evalBinOpNN

2021-11-23 Thread Gabor Marton via Phabricator via cfe-commits
martong marked 2 inline comments as done.
martong added a comment.

I'm attaching the coverage of the new test file for the related change:

  375 :   // Constraints may have changed since the creation of a 
bound SVal. Check if
  376 :   // the values can be simplified based on those new 
constraints.
  377  12 :   SVal simplifiedLhs = simplifySVal(state, lhs);
  378  12 :   SVal simplifiedRhs = simplifySVal(state, rhs);
  379  12 :   if (auto simplifiedLhsAsNonLoc = 
simplifiedLhs.getAs())
  380  12 : lhs = *simplifiedLhsAsNonLoc;
  381  12 :   if (auto simplifiedRhsAsNonLoc = 
simplifiedRhs.getAs())
  382  12 : rhs = *simplifiedRhsAsNonLoc;
  383 :




Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:378
+  SVal simplifiedLhs = simplifySVal(state, lhs);
+  SVal simplifiedRhs = simplifySVal(state, rhs);
+  if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs())

steakhal wrote:
> It seems like you simplify the `rhs` as well. Could we have a test for that?
Ok, I've added a new test case and reworked the existing a bit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113753

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


[PATCH] D113753: [Analyzer][Core] Better simplification in SimpleSValBuilder::evalBinOpNN

2021-11-23 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 389186.
martong marked an inline comment as done.
martong added a comment.

- Add new test case


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113753

Files:
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/test/Analysis/svalbuilder-simplify-in-evalbinop.cpp


Index: clang/test/Analysis/svalbuilder-simplify-in-evalbinop.cpp
===
--- /dev/null
+++ clang/test/Analysis/svalbuilder-simplify-in-evalbinop.cpp
@@ -0,0 +1,30 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+// Here we test whether the SValBuilder is capable to simplify existing
+// SVals based on a newly added constraints when evaluating a BinOp.
+
+void clang_analyzer_eval(bool);
+
+void test_evalBinOp_simplifies_lhs(int y) {
+  int x = y / 77;
+  if (y != 77)
+return;
+
+  // Below `x` is the LHS being simplified.
+  clang_analyzer_eval(x == 1); // expected-warning{{TRUE}}
+  (void)(x * y);
+}
+
+void test_evalBinOp_simplifies_rhs(int y) {
+  int x = y / 77;
+  if (y != 77)
+return;
+
+  // Below `x` is the RHS being simplified.
+  clang_analyzer_eval(1 == x); // expected-warning{{TRUE}}
+  (void)(x * y);
+}
Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -372,6 +372,15 @@
   NonLoc InputLHS = lhs;
   NonLoc InputRHS = rhs;
 
+  // Constraints may have changed since the creation of a bound SVal. Check if
+  // the values can be simplified based on those new constraints.
+  SVal simplifiedLhs = simplifySVal(state, lhs);
+  SVal simplifiedRhs = simplifySVal(state, rhs);
+  if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs())
+lhs = *simplifiedLhsAsNonLoc;
+  if (auto simplifiedRhsAsNonLoc = simplifiedRhs.getAs())
+rhs = *simplifiedRhsAsNonLoc;
+
   // Handle trivial case where left-side and right-side are the same.
   if (lhs == rhs)
 switch (op) {
@@ -619,16 +628,6 @@
 }
   }
 
-  // Does the symbolic expression simplify to a constant?
-  // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
-  // and try again.
-  SVal simplifiedLhs = simplifySVal(state, lhs);
-  if (simplifiedLhs != lhs)
-if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs()) {
-  lhs = *simplifiedLhsAsNonLoc;
-  continue;
-}
-
   // Is the RHS a constant?
   if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
 return MakeSymIntVal(Sym, op, *RHSValue, resultTy);


Index: clang/test/Analysis/svalbuilder-simplify-in-evalbinop.cpp
===
--- /dev/null
+++ clang/test/Analysis/svalbuilder-simplify-in-evalbinop.cpp
@@ -0,0 +1,30 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+// Here we test whether the SValBuilder is capable to simplify existing
+// SVals based on a newly added constraints when evaluating a BinOp.
+
+void clang_analyzer_eval(bool);
+
+void test_evalBinOp_simplifies_lhs(int y) {
+  int x = y / 77;
+  if (y != 77)
+return;
+
+  // Below `x` is the LHS being simplified.
+  clang_analyzer_eval(x == 1); // expected-warning{{TRUE}}
+  (void)(x * y);
+}
+
+void test_evalBinOp_simplifies_rhs(int y) {
+  int x = y / 77;
+  if (y != 77)
+return;
+
+  // Below `x` is the RHS being simplified.
+  clang_analyzer_eval(1 == x); // expected-warning{{TRUE}}
+  (void)(x * y);
+}
Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -372,6 +372,15 @@
   NonLoc InputLHS = lhs;
   NonLoc InputRHS = rhs;
 
+  // Constraints may have changed since the creation of a bound SVal. Check if
+  // the values can be simplified based on those new constraints.
+  SVal simplifiedLhs = simplifySVal(state, lhs);
+  SVal simplifiedRhs = simplifySVal(state, rhs);
+  if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs())
+lhs = *simplifiedLhsAsNonLoc;
+  if (auto simplifiedRhsAsNonLoc = simplifiedRhs.getAs())
+rhs = *simplifiedRhsAsNonLoc;
+
   // Handle trivial case where left-side and right-side are the same.
   if (lhs == rhs)
 switch (op) {
@@ -619,16 +628,6 @@
 }
   }
 
-  // Does the symbolic expression simplify to a constant?
-  // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
-  // and try aga

[PATCH] D114394: Compile-time computation of string attribute hashes

2021-11-23 Thread serge via Phabricator via cfe-commits
serge-sans-paille updated this revision to Diff 389187.
serge-sans-paille added a comment.

Remove static Dict and replace it by a dict attached to LLVMContext.

Some early benchmarks, on the SQLite amalgamation, through ` valgrind 
--tool=callgrind ./bin/clang -c -o/dev/null sqlite3.c`

Instruction count
Before: 6,072,172,562
After:6,011,551,695


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

https://reviews.llvm.org/D114394

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  llvm/include/llvm/Analysis/TargetLibraryInfo.h
  llvm/include/llvm/Analysis/VectorUtils.h
  llvm/include/llvm/CodeGen/CommandFlags.h
  llvm/include/llvm/IR/Assumptions.h
  llvm/include/llvm/IR/Attributes.h
  llvm/include/llvm/IR/Function.h
  llvm/include/llvm/IR/GlobalVariable.h
  llvm/include/llvm/IR/InstrTypes.h
  llvm/include/llvm/ProfileData/SampleProf.h
  llvm/lib/Analysis/InlineCost.cpp
  llvm/lib/AsmParser/LLParser.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/CodeGen/CommandFlags.cpp
  llvm/lib/IR/AttributeImpl.h
  llvm/lib/IR/Attributes.cpp
  llvm/lib/IR/Core.cpp
  llvm/lib/IR/DiagnosticInfo.cpp
  llvm/lib/IR/Function.cpp
  llvm/lib/IR/Instructions.cpp
  llvm/lib/IR/LLVMContextImpl.h
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Transforms/IPO/Attributor.cpp
  llvm/lib/Transforms/IPO/OpenMPOpt.cpp
  llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
  llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp
  llvm/lib/Transforms/Utils/CodeExtractor.cpp
  llvm/lib/Transforms/Utils/EntryExitInstrumenter.cpp

Index: llvm/lib/Transforms/Utils/EntryExitInstrumenter.cpp
===
--- llvm/lib/Transforms/Utils/EntryExitInstrumenter.cpp
+++ llvm/lib/Transforms/Utils/EntryExitInstrumenter.cpp
@@ -67,11 +67,13 @@
 }
 
 static bool runOnFunction(Function &F, bool PostInlining) {
-  StringRef EntryAttr = PostInlining ? "instrument-function-entry-inlined"
- : "instrument-function-entry";
+  AttributeKey EntryAttr =
+  PostInlining ? AttributeKey("instrument-function-entry-inlined")
+   : AttributeKey("instrument-function-entry");
 
-  StringRef ExitAttr = PostInlining ? "instrument-function-exit-inlined"
-: "instrument-function-exit";
+  AttributeKey ExitAttr = PostInlining
+  ? AttributeKey("instrument-function-exit-inlined")
+  : AttributeKey("instrument-function-exit");
 
   StringRef EntryFunc = F.getFnAttribute(EntryAttr).getValueAsString();
   StringRef ExitFunc = F.getFnAttribute(ExitAttr).getValueAsString();
Index: llvm/lib/Transforms/Utils/CodeExtractor.cpp
===
--- llvm/lib/Transforms/Utils/CodeExtractor.cpp
+++ llvm/lib/Transforms/Utils/CodeExtractor.cpp
@@ -888,7 +888,7 @@
   //   attribute can not be inherited.
   for (const auto &Attr : oldFunction->getAttributes().getFnAttrs()) {
 if (Attr.isStringAttribute()) {
-  if (Attr.getKindAsString() == "thunk")
+  if (Attr.getKindAsKey() == "thunk")
 continue;
 } else
   switch (Attr.getKindAsEnum()) {
Index: llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp
===
--- llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp
+++ llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp
@@ -1528,7 +1528,7 @@
 } // end anonymous namespace
 
 static StringRef getDeoptLowering(CallBase *Call) {
-  const char *DeoptLowering = "deopt-lowering";
+  const char DeoptLowering[] = "deopt-lowering";
   if (Call->hasFnAttr(DeoptLowering)) {
 // FIXME: Calls have a *really* confusing interface around attributes
 // with values.
Index: llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
@@ -4194,14 +4194,9 @@
 MemorySanitizerVisitor &MSV)
   : F(F), MS(MS), MSV(MSV) {
 AMD64FpEndOffset = AMD64FpEndOffsetSSE;
-for (const auto &Attr : F.getAttributes().getFnAttrs()) {
-  if (Attr.isStringAttribute() &&
-  (Attr.getKindAsString() == "target-features")) {
-if (Attr.getValueAsString().contains("-sse"))
-  AMD64FpEndOffset = AMD64FpEndOffsetNoSSE;
-break;
-  }
-}
+if (F.hasFnAttribute("target-features") &&
+F.getFnAttribute("target-features").getValueAsString().contains("-sse"))
+  AMD64FpEndOffset = AMD64FpEndOffsetNoSSE;
   }
 
   ArgKind classifyArgument(Value* arg) {
Index: llvm/lib/Transforms/IPO/OpenMPOpt.cpp
===
--- llvm/lib/Transforms/IPO/Ope

[PATCH] D114234: [clang][dataflow] Add base types for building dataflow analyses

2021-11-23 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 389189.
sgatev marked an inline comment as done.
sgatev added a comment.

Add a note about asserting the requirements of the CFG object.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114234

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Environment.h
  clang/lib/Analysis/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp

Index: clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
@@ -0,0 +1,34 @@
+//===- DataflowAnalysis.cpp ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#include 
+
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Optional.h"
+
+using namespace clang;
+using namespace dataflow;
+
+std::vector>
+runDataflowAnalysis(const CFG &Cfg, DataflowAnalysisDynamic &Analysis,
+const Environment &InitEnv) {
+  // FIXME: Consider enforcing that `Cfg` meets the requirements that
+  // are specified in the header. This could be done by remembering
+  // what options were used to build `Cfg` and asserting on them here.
+
+  // FIXME: Implement work list-based algorithm to compute the fixed
+  // point of `Analysis::transform` for every basic block in `Cfg`.
+  return {};
+}
Index: clang/lib/Analysis/FlowSensitive/CMakeLists.txt
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/CMakeLists.txt
@@ -0,0 +1,7 @@
+add_clang_library(clangAnalysisFlowSensitive
+  DataflowAnalysis.cpp
+
+  LINK_LIBS
+  clangAnalysis
+  clangAST
+  )
Index: clang/lib/Analysis/CMakeLists.txt
===
--- clang/lib/Analysis/CMakeLists.txt
+++ clang/lib/Analysis/CMakeLists.txt
@@ -44,3 +44,4 @@
   )
 
 add_subdirectory(plugins)
+add_subdirectory(FlowSensitive)
Index: clang/include/clang/Analysis/FlowSensitive/Environment.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/Environment.h
@@ -0,0 +1,27 @@
+//===-- Environment.h ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines an Environment class that is used by dataflow analyses
+//  that run over Control-Flow Graphs (CFGs) to keep track of the state of the
+//  program at given program points.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+
+namespace clang {
+namespace dataflow {
+
+/// Holds the state of the program (store and heap) at a given program point.
+class Environment {};
+
+} // namespace dataflow
+} // namespace clang
+
+#endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
Index: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -0,0 +1,160 @@
+//===- DataflowAnalysis.h ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+
+#include 
+#include 
+
+#include "clang/AST/ASTContext.h"
+#in

[PATCH] D114370: [clangd] IncludeCleaner: Attribute symbols from non self-contained headers to their parents

2021-11-23 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:262
+ ID != SM.getMainFileID() && FE &&
+ !isSelfContainedHeader(PP, ID, FE);) {
+  ID = SM.getFileID(SM.getIncludeLoc(ID));

kbobyrev wrote:
> sammccall wrote:
> > it seems like we'd be better off storing the "is-self-contained" in the 
> > IncludeStructure and looking up the HeaderID here rather than asking the 
> > preprocessor. That way we rely on info that's better obtained at preamble 
> > build time.
> I am slightly confused: we don't really have the `IncludeStructure` here and 
> it is logically detached from the `IncludeStructure` processing. We'd still 
> have to unroll the chain of FIDs in here, so the only difference would be 
> querying `IncludeStructure` data for the cached `isSelfContainedHeader` 
> value, is that right? Why is obtaining that info at preamble build time 
> better?
the call-site has access to ParsedAST, hence the IncludeStructure. I believe 
the main reasoning behind Sam's suggestion is performing these lookups once 
while building the preamble and sharing it afterwards (we can even do the IO 
there).



Comment at: clang-tools-extra/clangd/SourceCode.cpp:56
+// Is Line an #if or #ifdef directive?
+static bool isIf(llvm::StringRef Line) {
+  Line = Line.ltrim();

no need for static here (and other places below)



Comment at: clang-tools-extra/clangd/SourceCode.h:332
+bool isSelfContainedHeader(const Preprocessor &PP, FileID FID,
+   const FileEntry *FE, bool ExpensiveCheck = false);
+

i'd suggest `AllowIO` rather than `ExpensiveCheck`



Comment at: clang-tools-extra/clangd/index/SymbolCollector.cpp:283
   // Is Line an #if or #ifdef directive?
   static bool isIf(llvm::StringRef Line) {
 Line = Line.ltrim();

can you also delete this and the other helpers?



Comment at: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp:346
+  // headers to header-guarded ones.
+  for (const auto &Key : ReferencedFileNames.keys()) {
+llvm::outs() << "Key: " << Key << '\n';

looks like a debug artifact


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114370

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


[PATCH] D114249: [clang-tidy] performance-unnecessary-copy-initialization: Fix false negative.

2021-11-23 Thread Felix Berger via Phabricator via cfe-commits
flx accepted this revision.
flx added inline comments.
This revision is now accepted and ready to land.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp:228-232
+void PositiveOperatorCallConstValueParam(const Container* 
C) {
+  const auto AutoAssigned = (*C)[42];
+  // TODO-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 
'AutoAssigned'
+  // TODO-FIXES: const auto& AutoAssigned = (*C)[42];
+  AutoAssigned.constMethod();

Would you mind adding this test also to the file testing the exclusion of 
containers:

https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization-excluded-container-types.cpp

This would cover whether the type matching of pointer types works for excluded 
container types.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114249

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


[PATCH] D114439: [Annotation] Allow parameter pack expansions in annotate attribute

2021-11-23 Thread Steffen Larsen via Phabricator via cfe-commits
steffenlarsen created this revision.
steffenlarsen added reviewers: erichkeane, aaron.ballman, Tyker, Naghasan.
Herald added a subscriber: jdoerfert.
steffenlarsen requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

These changes make the Clang parser recognize parameter pack expansion in 
attribute arguments and consume them if the attribute is marked as supporting 
parameter pack expansions.
Currently only the `clang::annotate` attribute will support parameter pack 
expansions in its arguments. The parser will issue an error diagnostic if other 
attributes are passed parameter pack expansion arguments.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114439

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/Parser/cxx0x-attributes.cpp
  clang/test/SemaTemplate/attributes.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp

Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -1697,6 +1697,22 @@
   OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
 }
 
+// Emits the ParmExpansionArgsSupport property for attributes.
+static void emitClangAttrParmExpansionArgsSupportList(RecordKeeper &Records,
+  raw_ostream &OS) {
+  OS << "#if defined(CLANG_ATTR_PARM_EXPANSION_ARGS_SUPPORT_LIST)\n";
+  std::vector Attrs = Records.getAllDerivedDefinitions("Attr");
+
+  for (const auto *Attr : Attrs) {
+if (Attr->getValueAsBit("ParmExpansionArgsSupport")) {
+  std::vector Spellings = GetFlattenedSpellings(*Attr);
+  for (const auto &I : Spellings)
+OS << ".Case(\"" << I.name() << "\", true)\n";
+}
+  }
+  OS << "#endif // CLANG_ATTR_PARM_EXPANSION_ARGS_SUPPORT_LIST\n\n";
+}
+
 static bool hasGNUorCXX11Spelling(const Record &Attribute) {
   std::vector Spellings = GetFlattenedSpellings(Attribute);
   for (const auto &I : Spellings) {
@@ -4221,6 +4237,7 @@
   emitClangAttrThisIsaIdentifierArgList(Records, OS);
   emitClangAttrTypeArgList(Records, OS);
   emitClangAttrLateParsedList(Records, OS);
+  emitClangAttrParmExpansionArgsSupportList(Records, OS);
 }
 
 void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
Index: clang/test/SemaTemplate/attributes.cpp
===
--- clang/test/SemaTemplate/attributes.cpp
+++ clang/test/SemaTemplate/attributes.cpp
@@ -64,6 +64,23 @@
 template [[clang::annotate("ANNOTATE_FOO"), clang::annotate("ANNOTATE_BAR")]] void HasAnnotations();
 void UseAnnotations() { HasAnnotations(); }
 
+// CHECK:  FunctionTemplateDecl {{.*}} HasPackAnnotations
+// CHECK:AnnotateAttr {{.*}} "ANNOTATE_BAZ"
+// CHECK:  FunctionDecl {{.*}} HasPackAnnotations
+// CHECK:TemplateArgument{{.*}} pack
+// CHECK-NEXT: TemplateArgument{{.*}} integral 1
+// CHECK-NEXT: TemplateArgument{{.*}} integral 2
+// CHECK-NEXT: TemplateArgument{{.*}} integral 3
+// CHECK:AnnotateAttr {{.*}} "ANNOTATE_BAZ"
+// CHECK:  ConstantExpr {{.*}} 'int'
+// CHECK-NEXT:   value: Int 1
+// CHECK:  ConstantExpr {{.*}} 'int'
+// CHECK-NEXT:   value: Int 2
+// CHECK:  ConstantExpr {{.*}} 'int'
+// CHECK-NEXT:   value: Int 3
+template  [[clang::annotate("ANNOTATE_BAZ", Is...)]] void HasPackAnnotations();
+void UsePackAnnotations() { HasPackAnnotations<1, 2, 3>(); }
+
 namespace preferred_name {
   int x [[clang::preferred_name("frank")]]; // expected-error {{expected a type}}
   int y [[clang::preferred_name(int)]]; // expected-warning {{'preferred_name' attribute only applies to class templates}}
Index: clang/test/Parser/cxx0x-attributes.cpp
===
--- clang/test/Parser/cxx0x-attributes.cpp
+++ clang/test/Parser/cxx0x-attributes.cpp
@@ -258,8 +258,10 @@
   [[]] return;
 }
 
-template void variadic() {
+template  void variadic() {
   void bar [[noreturn...]] (); // expected-error {{attribute 'noreturn' cannot be used as an attribute pack}}
+  void baz [[clang::no_sanitize(Is...)]] (); // expected-error {{attribute 'no_sanitize' does not support parameter pack expansion in arguments}}
+  void boo [[unknown::foo(Is...)]] ();   // expected-warning {{unknown attribute 'foo' ignored}}
 }
 
 // Expression tests
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -189,13 +189,9 @@
   EnterExpressionEvaluationContext Unevaluated(
   S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
   SmallVector Args;
-  Args.reserv

[PATCH] D113451: [PowerPC] [Clang] Enable Intel intrinsics support on FreeBSD

2021-11-23 Thread Kamau Bridgeman via Phabricator via cfe-commits
kamaub added a comment.

Test case `clang/test/CodeGen/ppc-mm-malloc.c` fails on powerpc BE buildbots 
with this changeset
https://lab.llvm.org/buildbot/#/builders/93/builds/6031
https://lab.llvm.org/buildbot/#/builders/100/builds/10836
https://lab.llvm.org/buildbot/#/builders/52/builds/12719

  *** TEST 'Clang :: CodeGen/ppc-mm-malloc.c' FAILED 

  Script:
  --
  : 'RUN: at line 9';   
/home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/stage1/bin/clang
 -target powerpc64-unknown-linux-gnu -S -emit-llvm 
/home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/llvm/clang/test/CodeGen/ppc-mm-malloc.c
 -fno-discard-value-names -mllvm -disable-llvm-optzns -o - | llvm-cxxfilt | 
/home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/stage1/bin/FileCheck
 
/home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/llvm/clang/test/CodeGen/ppc-mm-malloc.c
  : 'RUN: at line 10';   
/home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/stage1/bin/clang
 -target powerpc64-unknown-freebsd13.0 -S -emit-llvm 
/home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/llvm/clang/test/CodeGen/ppc-mm-malloc.c
 -fno-discard-value-names -mllvm -disable-llvm-optzns -o - | llvm-cxxfilt | 
/home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/stage1/bin/FileCheck
 
/home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/llvm/clang/test/CodeGen/ppc-mm-malloc.c
  --
  Exit Code: 2
  Command Output (stderr):
  --
  In file included from 
/home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/llvm/clang/test/CodeGen/ppc-mm-malloc.c:12:
  In file included from 
/home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/stage1/lib/clang/14.0.0/include/ppc_wrappers/mm_malloc.h:15:
  In file included from /usr/include/stdlib.h:25:
  In file included from /usr/include/bits/libc-header-start.h:33:
  In file included from /usr/include/features.h:434:
  /usr/include/gnu/stubs.h:14:11: fatal error: 'gnu/stubs-64-v2.h' file not 
found
  # include 
^~~
  1 error generated.
  FileCheck error: '' is empty.
  FileCheck command line:  
/home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/stage1/bin/FileCheck
 
/home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/llvm/clang/test/CodeGen/ppc-mm-malloc.c
  --
  




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113451

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


[PATCH] D113451: [PowerPC] [Clang] Enable Intel intrinsics support on FreeBSD

2021-11-23 Thread Jinsong Ji via Phabricator via cfe-commits
jsji added a comment.

In D113451#3148815 , @kamaub wrote:

> Test case `clang/test/CodeGen/ppc-mm-malloc.c` fails on powerpc BE buildbots 
> with this changeset
> https://lab.llvm.org/buildbot/#/builders/93/builds/6031
> https://lab.llvm.org/buildbot/#/builders/100/builds/10836
> https://lab.llvm.org/buildbot/#/builders/52/builds/12719
>
>   *** TEST 'Clang :: CodeGen/ppc-mm-malloc.c' FAILED 
> 
>   Script:
>   --
>   : 'RUN: at line 9';   
> /home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/stage1/bin/clang
>  -target powerpc64-unknown-linux-gnu -S -emit-llvm 
> /home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/llvm/clang/test/CodeGen/ppc-mm-malloc.c
>  -fno-discard-value-names -mllvm -disable-llvm-optzns -o - | llvm-cxxfilt | 
> /home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/stage1/bin/FileCheck
>  
> /home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/llvm/clang/test/CodeGen/ppc-mm-malloc.c
>   : 'RUN: at line 10';   
> /home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/stage1/bin/clang
>  -target powerpc64-unknown-freebsd13.0 -S -emit-llvm 
> /home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/llvm/clang/test/CodeGen/ppc-mm-malloc.c
>  -fno-discard-value-names -mllvm -disable-llvm-optzns -o - | llvm-cxxfilt | 
> /home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/stage1/bin/FileCheck
>  
> /home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/llvm/clang/test/CodeGen/ppc-mm-malloc.c
>   --
>   Exit Code: 2
>   Command Output (stderr):
>   --
>   In file included from 
> /home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/llvm/clang/test/CodeGen/ppc-mm-malloc.c:12:
>   In file included from 
> /home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/stage1/lib/clang/14.0.0/include/ppc_wrappers/mm_malloc.h:15:
>   In file included from /usr/include/stdlib.h:25:
>   In file included from /usr/include/bits/libc-header-start.h:33:
>   In file included from /usr/include/features.h:434:
>   /usr/include/gnu/stubs.h:14:11: fatal error: 'gnu/stubs-64-v2.h' file not 
> found
>   # include 
> ^~~
>   1 error generated.
>   FileCheck error: '' is empty.
>   FileCheck command line:  
> /home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/stage1/bin/FileCheck
>  
> /home/buildbots/ppc64be-clang-multistage-test/clang-ppc64be-multistage/llvm/clang/test/CodeGen/ppc-mm-malloc.c
>   --
>   

Thanks @kamaub ! Removed the offending line in 
b0784d1d14246e5d662172e9af6e85776b81fdf0 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113451

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


[clang] e13246a - [HIP] Add HIP scope atomic operations

2021-11-23 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2021-11-23T10:13:37-05:00
New Revision: e13246a2ec3dfc13838d43099ca9111c780d2c5e

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

LOG: [HIP] Add HIP scope atomic operations

Add an AtomicScopeModel for HIP and support for OpenCL builtins
that are missing in HIP.

Patch by: Michael Liao

Revised by: Anshil Ghandi

Reviewed by: Yaxun Liu

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

Added: 
clang/test/CodeGenCUDA/atomic-ops.cu

Modified: 
clang/include/clang/AST/Expr.h
clang/include/clang/Basic/Builtins.def
clang/include/clang/Basic/SyncScope.h
clang/lib/AST/Expr.cpp
clang/lib/CodeGen/CGAtomic.cpp
clang/lib/CodeGen/TargetInfo.cpp
clang/lib/Frontend/InitPreprocessor.cpp
clang/lib/Sema/SemaChecking.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 991abef733637..246585e1205fa 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -6305,6 +6305,7 @@ class AtomicExpr : public Expr {
   bool isCmpXChg() const {
 return getOp() == AO__c11_atomic_compare_exchange_strong ||
getOp() == AO__c11_atomic_compare_exchange_weak ||
+   getOp() == AO__hip_atomic_compare_exchange_strong ||
getOp() == AO__opencl_atomic_compare_exchange_strong ||
getOp() == AO__opencl_atomic_compare_exchange_weak ||
getOp() == AO__atomic_compare_exchange ||
@@ -6341,7 +6342,10 @@ class AtomicExpr : public Expr {
 auto Kind =
 (Op >= AO__opencl_atomic_load && Op <= AO__opencl_atomic_fetch_max)
 ? AtomicScopeModelKind::OpenCL
-: AtomicScopeModelKind::None;
+: (Op >= AO__hip_atomic_compare_exchange_strong &&
+   Op <= AO__hip_atomic_fetch_max)
+  ? AtomicScopeModelKind::HIP
+  : AtomicScopeModelKind::None;
 return AtomicScopeModel::create(Kind);
   }
 

diff  --git a/clang/include/clang/Basic/Builtins.def 
b/clang/include/clang/Basic/Builtins.def
index b05777889e79a..1f7680e0d923c 100644
--- a/clang/include/clang/Basic/Builtins.def
+++ b/clang/include/clang/Basic/Builtins.def
@@ -854,6 +854,18 @@ ATOMIC_BUILTIN(__opencl_atomic_fetch_max, "v.", "t")
 ATOMIC_BUILTIN(__atomic_fetch_min, "v.", "t")
 ATOMIC_BUILTIN(__atomic_fetch_max, "v.", "t")
 
+// HIP atomic builtins.
+// FIXME: Is `__hip_atomic_compare_exchange_n` or
+// `__hip_atomic_compare_exchange_weak` needed?
+ATOMIC_BUILTIN(__hip_atomic_compare_exchange_strong, "v.", "t")
+ATOMIC_BUILTIN(__hip_atomic_exchange, "v.", "t")
+ATOMIC_BUILTIN(__hip_atomic_fetch_add, "v.", "t")
+ATOMIC_BUILTIN(__hip_atomic_fetch_and, "v.", "t")
+ATOMIC_BUILTIN(__hip_atomic_fetch_or, "v.", "t")
+ATOMIC_BUILTIN(__hip_atomic_fetch_xor, "v.", "t")
+ATOMIC_BUILTIN(__hip_atomic_fetch_min, "v.", "t")
+ATOMIC_BUILTIN(__hip_atomic_fetch_max, "v.", "t")
+
 #undef ATOMIC_BUILTIN
 
 // Non-overloaded atomic builtins.

diff  --git a/clang/include/clang/Basic/SyncScope.h 
b/clang/include/clang/Basic/SyncScope.h
index ce8fb9cbed131..34703310af2b6 100644
--- a/clang/include/clang/Basic/SyncScope.h
+++ b/clang/include/clang/Basic/SyncScope.h
@@ -40,6 +40,11 @@ namespace clang {
 ///   Update getAsString.
 ///
 enum class SyncScope {
+  HIPSingleThread,
+  HIPWavefront,
+  HIPWorkgroup,
+  HIPAgent,
+  HIPSystem,
   OpenCLWorkGroup,
   OpenCLDevice,
   OpenCLAllSVMDevices,
@@ -49,6 +54,16 @@ enum class SyncScope {
 
 inline llvm::StringRef getAsString(SyncScope S) {
   switch (S) {
+  case SyncScope::HIPSingleThread:
+return "hip_singlethread";
+  case SyncScope::HIPWavefront:
+return "hip_wavefront";
+  case SyncScope::HIPWorkgroup:
+return "hip_workgroup";
+  case SyncScope::HIPAgent:
+return "hip_agent";
+  case SyncScope::HIPSystem:
+return "hip_system";
   case SyncScope::OpenCLWorkGroup:
 return "opencl_workgroup";
   case SyncScope::OpenCLDevice:
@@ -62,7 +77,7 @@ inline llvm::StringRef getAsString(SyncScope S) {
 }
 
 /// Defines the kind of atomic scope models.
-enum class AtomicScopeModelKind { None, OpenCL };
+enum class AtomicScopeModelKind { None, OpenCL, HIP };
 
 /// Defines the interface for synch scope model.
 class AtomicScopeModel {
@@ -138,6 +153,58 @@ class AtomicScopeOpenCLModel : public AtomicScopeModel {
   }
 };
 
+/// Defines the synch scope model for HIP.
+class AtomicScopeHIPModel : public AtomicScopeModel {
+public:
+  /// The enum values match the pre-defined macros
+  /// __HIP_MEMORY_SCOPE_*, which are used to define memory_scope_*
+  /// enums in hip-c.h.
+  enum ID {
+SingleThread = 1,
+Wavefront = 2,
+Workgroup = 3,
+Agent = 4,
+System = 5,
+Last = System
+  };
+
+  AtomicScopeHIPModel() {}
+
+  SyncScope map(unsigned 

[PATCH] D113925: [HIP] Add HIP scope atomic operations

2021-11-23 Thread Yaxun Liu 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 rGe13246a2ec3d: [HIP] Add HIP scope atomic operations 
(authored by yaxunl).

Changed prior to commit:
  https://reviews.llvm.org/D113925?vs=387668&id=389195#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113925

Files:
  clang/include/clang/AST/Expr.h
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/SyncScope.h
  clang/lib/AST/Expr.cpp
  clang/lib/CodeGen/CGAtomic.cpp
  clang/lib/CodeGen/TargetInfo.cpp
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGenCUDA/atomic-ops.cu

Index: clang/test/CodeGenCUDA/atomic-ops.cu
===
--- /dev/null
+++ clang/test/CodeGenCUDA/atomic-ops.cu
@@ -0,0 +1,302 @@
+// RUN: %clang_cc1 -x hip -std=c++11 -triple amdgcn -fcuda-is-device -emit-llvm %s -o - | FileCheck %s
+#include "Inputs/cuda.h"
+
+// CHECK-LABEL: @_Z24atomic32_op_singlethreadPiii
+// CHECK: cmpxchg i32* {{%[0-9]+}}, i32 {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("singlethread-one-as")
+// CHECK: atomicrmw xchg i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("singlethread-one-as")
+// CHECK: atomicrmw add i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("singlethread-one-as")
+// CHECK: atomicrmw and i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("singlethread-one-as")
+// CHECK: atomicrmw or i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("singlethread-one-as")
+// CHECK: atomicrmw xor i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("singlethread-one-as")
+// CHECK: atomicrmw min i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("singlethread-one-as")
+// CHECK: atomicrmw max i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("singlethread-one-as")
+__device__ int atomic32_op_singlethread(int *ptr, int val, int desired) {
+  bool flag = __hip_atomic_compare_exchange_strong(ptr, &val, desired, __ATOMIC_RELAXED, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SINGLETHREAD);
+  val = __hip_atomic_exchange(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SINGLETHREAD);
+  val = __hip_atomic_fetch_add(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SINGLETHREAD);
+  val = __hip_atomic_fetch_and(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SINGLETHREAD);
+  val = __hip_atomic_fetch_or(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SINGLETHREAD);
+  val = __hip_atomic_fetch_xor(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SINGLETHREAD);
+  val = __hip_atomic_fetch_min(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SINGLETHREAD);
+  val = __hip_atomic_fetch_max(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SINGLETHREAD);
+  return flag ? val : desired;
+}
+
+// CHECK-LABEL: @_Z25atomicu32_op_singlethreadPjjj
+// CHECK: atomicrmw umin i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("singlethread-one-as")
+// CHECK: atomicrmw umax i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("singlethread-one-as")
+__device__ unsigned int atomicu32_op_singlethread(unsigned int *ptr, unsigned int val, unsigned int desired) {
+  val = __hip_atomic_fetch_min(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SINGLETHREAD);
+  val = __hip_atomic_fetch_max(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SINGLETHREAD);
+  return val;
+}
+
+// CHECK-LABEL: @_Z21atomic32_op_wavefrontPiii
+// CHECK: cmpxchg i32* {{%[0-9]+}}, i32 {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("wavefront-one-as")
+// CHECK: atomicrmw xchg i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("wavefront-one-as")
+// CHECK: atomicrmw add i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("wavefront-one-as")
+// CHECK: atomicrmw and i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("wavefront-one-as")
+// CHECK: atomicrmw or i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("wavefront-one-as")
+// CHECK: atomicrmw xor i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("wavefront-one-as")
+// CHECK: atomicrmw min i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("wavefront-one-as")
+// CHECK: atomicrmw max i32* {{%[0-9]+}}, i32 {{%[0-9]+}} syncscope("wavefront-one-as")
+__device__ int atomic32_op_wavefront(int *ptr, int val, int desired) {
+  bool flag = __hip_atomic_compare_exchange_strong(ptr, &val, desired, __ATOMIC_RELAXED, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_WAVEFRONT);
+  val = __hip_atomic_exchange(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_WAVEFRONT);
+  val = __hip_atomic_fetch_add(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_WAVEFRONT);
+  val = __hip_atomic_fetch_and(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_WAVEFRONT);
+  val = __hip_atomic_fetch_or(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_WAVEFRONT);
+  val = __hip_atomic_fetch_xor(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_WAVEFRONT);
+  val = __hip_atomic_fetch_min(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_WAVEFRONT);
+  val = __hip_atomic_fetch_max(ptr, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_WAVEFRONT);
+  return flag ? va

[PATCH] D113049: [AIX] Disable tests that fail because of no 64-bit XCOFF object file support

2021-11-23 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan updated this revision to Diff 389196.
Jake-Egan added a comment.

Thanks for the review. I updated the patch to use lit.cfg.py to filter tests 
that use obj options. For tests that don't use the option or has an individual 
folder, I changed them to UNSUPPORTED instead of XFAIL.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113049

Files:
  clang/test/ASTMerge/anonymous-fields/test.cpp
  clang/test/ASTMerge/codegen-body/test.c
  clang/test/ASTMerge/injected-class-name-decl/test.cpp
  clang/test/ClangScanDeps/modules-full-by-mod-name.cpp
  clang/test/ClangScanDeps/modules-pch-common-submodule.c
  clang/test/ClangScanDeps/modules-pch-common-via-submodule.c
  clang/test/ClangScanDeps/modules-pch.c
  clang/test/ClangScanDeps/resource_directory.c
  clang/test/Driver/as-version.s
  clang/test/Driver/cc-print-proc-stat.c
  clang/test/Driver/compilation_database.c
  clang/test/Driver/modules-ts.cpp
  clang/test/Driver/report-stat.c
  clang/test/lit.cfg.py
  llvm/test/LTO/X86/remangle_intrinsics.ll
  llvm/test/lit.cfg.py
  llvm/unittests/DebugInfo/DWARF/DWARFDebugInfoTest.cpp

Index: llvm/unittests/DebugInfo/DWARF/DWARFDebugInfoTest.cpp
===
--- llvm/unittests/DebugInfo/DWARF/DWARFDebugInfoTest.cpp
+++ llvm/unittests/DebugInfo/DWARF/DWARFDebugInfoTest.cpp
@@ -1131,7 +1131,11 @@
   EXPECT_STREQ(String1, *Extracted3);
 }
 
+#if defined(_AIX) && defined(__64BIT__)
+TEST(DWARFDebugInfo, DISABLED_TestEmptyStringOffsets) {
+#else
 TEST(DWARFDebugInfo, TestEmptyStringOffsets) {
+#endif
   Triple Triple = getNormalizedDefaultTargetTriple();
   if (!isObjectEmissionSupported(Triple))
 return;
@@ -1160,7 +1164,11 @@
   DwarfContext->getDWARFObj().getStrOffsetsSection().Data.empty());
 }
 
+#if defined(_AIX) && defined(__64BIT__)
+TEST(DWARFDebugInfo, DISABLED_TestRelations) {
+#else
 TEST(DWARFDebugInfo, TestRelations) {
+#endif
   Triple Triple = getNormalizedDefaultTargetTriple();
   if (!isObjectEmissionSupported(Triple))
 return;
@@ -1347,7 +1355,11 @@
   EXPECT_FALSE(DefaultDie.getSibling().isValid());
 }
 
+#if defined(_AIX) && defined(__64BIT__)
+TEST(DWARFDebugInfo, DISABLED_TestChildIterators) {
+#else
 TEST(DWARFDebugInfo, TestChildIterators) {
+#endif
   Triple Triple = getNormalizedDefaultTargetTriple();
   if (!isObjectEmissionSupported(Triple))
 return;
@@ -1456,7 +1468,11 @@
   EXPECT_EQ(CUDie.begin(), CUDie.end());
 }
 
+#if defined(_AIX) && defined(__64BIT__)
+TEST(DWARFDebugInfo, DISABLED_TestAttributeIterators) {
+#else
 TEST(DWARFDebugInfo, TestAttributeIterators) {
+#endif
   Triple Triple = getNormalizedDefaultTargetTriple();
   if (!isObjectEmissionSupported(Triple))
 return;
@@ -1518,7 +1534,11 @@
   EXPECT_EQ(E, ++I);
 }
 
+#if defined(_AIX) && defined(__64BIT__)
+TEST(DWARFDebugInfo, DISABLED_TestFindRecurse) {
+#else
 TEST(DWARFDebugInfo, TestFindRecurse) {
+#endif
   Triple Triple = getNormalizedDefaultTargetTriple();
   if (!isObjectEmissionSupported(Triple))
 return;
@@ -1732,7 +1752,11 @@
   // Test
 }
 
+#if defined(_AIX) && defined(__64BIT__)
+TEST(DWARFDebugInfo, DISABLED_TestFindAttrs) {
+#else
 TEST(DWARFDebugInfo, TestFindAttrs) {
+#endif
   Triple Triple = getNormalizedDefaultTargetTriple();
   if (!isObjectEmissionSupported(Triple))
 return;
@@ -1795,7 +1819,11 @@
   EXPECT_EQ(DieMangled, toString(NameOpt, ""));
 }
 
+#if defined(_AIX) && defined(__64BIT__)
+TEST(DWARFDebugInfo, DISABLED_TestImplicitConstAbbrevs) {
+#else
 TEST(DWARFDebugInfo, TestImplicitConstAbbrevs) {
+#endif
   Triple Triple = getNormalizedDefaultTargetTriple();
   if (!isObjectEmissionSupported(Triple))
 return;
Index: llvm/test/lit.cfg.py
===
--- llvm/test/lit.cfg.py
+++ llvm/test/lit.cfg.py
@@ -402,3 +402,22 @@
 
 if "MemoryWithOrigins" in config.llvm_use_sanitizer:
 config.available_features.add('use_msan_with_origins')
+
+def exclude_unsupported_files_for_aix(dirname):
+   for filename in os.listdir(dirname):
+   source_path = os.path.join( dirname, filename)
+   if os.path.isdir(source_path):
+   continue
+   f = open(source_path, 'r')
+   try:
+  data = f.read()
+  # 64-bit object files are not supported on AIX, so exclude the tests.
+  if ('-emit-obj' in data or '-filetype=obj' in data) and '64' in config.target_triple:
+config.excludes += [ filename ]
+   finally:
+  f.close()
+
+if 'aix' in config.target_triple:
+for directory in ('/CodeGen/X86', '/DebugInfo', '/DebugInfo/X86', '/DebugInfo/Generic', '/LTO/X86', '/Linker'):
+exclude_unsupported_files_for_aix(config.test_source_root + directory)
+
Index: llvm/test/LTO/X86/remangle_intrinsics.ll
===
--- llvm/test/LTO/X86/remangle_intrinsics.ll
+++ llvm/test/

[PATCH] D113753: [Analyzer][Core] Better simplification in SimpleSValBuilder::evalBinOpNN

2021-11-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.
This revision is now accepted and ready to land.

Awesome!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113753

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


[PATCH] D114249: [clang-tidy] performance-unnecessary-copy-initialization: Fix false negative.

2021-11-23 Thread Clement Courbet via Phabricator via cfe-commits
courbet updated this revision to Diff 389197.
courbet added a comment.

add container exclusion tests for operators.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114249

Files:
  clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
  
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization-excluded-container-types.cpp
  
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
@@ -3,11 +3,19 @@
 template 
 struct Iterator {
   void operator++();
-  const T &operator*() const;
+  T &operator*() const;
   bool operator!=(const Iterator &) const;
   typedef const T &const_reference;
 };
 
+template 
+struct ConstIterator {
+  void operator++();
+  const T &operator*() const;
+  bool operator!=(const ConstIterator &) const;
+  typedef const T &const_reference;
+};
+
 struct ExpensiveToCopyType {
   ExpensiveToCopyType();
   virtual ~ExpensiveToCopyType();
@@ -15,8 +23,6 @@
   using ConstRef = const ExpensiveToCopyType &;
   ConstRef referenceWithAlias() const;
   const ExpensiveToCopyType *pointer() const;
-  Iterator begin() const;
-  Iterator end() const;
   void nonConstMethod();
   bool constMethod() const;
   template 
@@ -24,6 +30,21 @@
   operator int() const; // Implicit conversion to int.
 };
 
+template 
+struct Container {
+  bool empty() const;
+  const T& operator[](int) const;
+  const T& operator[](int);
+  Iterator begin();
+  Iterator end();
+  ConstIterator begin() const;
+  ConstIterator end() const;
+  void nonConstMethod();
+  bool constMethod() const;
+};
+
+using ExpensiveToCopyContainerAlias = Container;
+
 struct TrivialToCopyType {
   const TrivialToCopyType &reference() const;
 };
@@ -138,6 +159,94 @@
   VarCopyConstructed.constMethod();
 }
 
+void PositiveOperatorCallConstReferenceParam(const Container &C) {
+  const auto AutoAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 'AutoAssigned'
+  // CHECK-FIXES: const auto& AutoAssigned = C[42];
+  AutoAssigned.constMethod();
+
+  const auto AutoCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 'AutoCopyConstructed'
+  // CHECK-FIXES: const auto& AutoCopyConstructed(C[42]);
+  AutoCopyConstructed.constMethod();
+
+  const ExpensiveToCopyType VarAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 'VarAssigned'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarAssigned = C[42];
+  VarAssigned.constMethod();
+
+  const ExpensiveToCopyType VarCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 'VarCopyConstructed'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarCopyConstructed(C[42]);
+  VarCopyConstructed.constMethod();
+}
+
+void PositiveOperatorCallConstValueParam(const Container C) {
+  const auto AutoAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 'AutoAssigned'
+  // CHECK-FIXES: const auto& AutoAssigned = C[42];
+  AutoAssigned.constMethod();
+
+  const auto AutoCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 'AutoCopyConstructed'
+  // CHECK-FIXES: const auto& AutoCopyConstructed(C[42]);
+  AutoCopyConstructed.constMethod();
+
+  const ExpensiveToCopyType VarAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 'VarAssigned'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarAssigned = C[42];
+  VarAssigned.constMethod();
+
+  const ExpensiveToCopyType VarCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 'VarCopyConstructed'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarCopyConstructed(C[42]);
+  VarCopyConstructed.constMethod();
+}
+
+void PositiveOperatorCallConstValueParamAlias(const ExpensiveToCopyContainerAlias C) {
+  const auto AutoAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 'AutoAssigned'
+  // CHECK-FIXES: const auto& AutoAssigned = C[42];
+  AutoAssigned.constMethod();
+
+  const auto AutoCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 'AutoCopyConstructed'
+  // CHECK-FIXES: const auto& AutoCopyConstructed(C[42]);
+  AutoCopyConstructed.constMethod();
+
+  const ExpensiveToCopyType VarAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 'VarAssigned'
+  // CHECK-FIXES: const ExpensiveToCopyTyp

[PATCH] D103317: [Analyzer][Core] Make SValBuilder to better simplify svals with 3 symbols in the tree

2021-11-23 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 389198.
martong marked 6 inline comments as done.
martong added a comment.

- Return explicitly with UndefinedVal
- Unify test cases (return 0 -> return)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103317

Files:
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/test/Analysis/svalbuilder-simplify-compound-svals.cpp
  clang/test/Analysis/taint-tester.c

Index: clang/test/Analysis/taint-tester.c
===
--- clang/test/Analysis/taint-tester.c
+++ clang/test/Analysis/taint-tester.c
@@ -59,7 +59,7 @@
   int tty = xy.y; // expected-warning + {{tainted}}
 }
 
-void BitwiseOp(int in, char inn) {
+void BitwiseOp(int in, char inn, int zz) {
   // Taint on bitwise operations, integer to integer cast.
   int m;
   int x = 0;
@@ -67,11 +67,12 @@
   int y = (in << (x << in)) * 5;// expected-warning + {{tainted}}
   // The next line tests integer to integer cast.
   int z = y & inn; // expected-warning + {{tainted}}
-  if (y == 5) // expected-warning + {{tainted}}
+  if (y == zz) { // expected-warning + {{tainted}}
 m = z | z;// expected-warning + {{tainted}}
+  }
   else
 m = inn;
-  int mm = m; // expected-warning + {{tainted}}
+  int mm = m; // expected-warning 1 {{tainted}}
 }
 
 // Test getenv.
Index: clang/test/Analysis/svalbuilder-simplify-compound-svals.cpp
===
--- /dev/null
+++ clang/test/Analysis/svalbuilder-simplify-compound-svals.cpp
@@ -0,0 +1,69 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+// Here we test whether the SValBuilder is capable to simplify existing
+// compound SVals (where there are at leaset 3 symbols in the tree) based on
+// newly added constraints.
+
+void clang_analyzer_eval(bool);
+void clang_analyzer_warnIfReached();
+
+void test_left_tree_constrained(int x, int y, int z) {
+  if (x + y + z != 0)
+return;
+  if (x + y != 0)
+return;
+  clang_analyzer_eval(x + y + z == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x + y == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(z == 0); // expected-warning{{TRUE}}
+  x = y = z = 1;
+  return;
+}
+
+void test_right_tree_constrained(int x, int y, int z) {
+  if (x + y * z != 0)
+return;
+  if (y * z != 0)
+return;
+  clang_analyzer_eval(x + y * z == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(y * z == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x == 0); // expected-warning{{TRUE}}
+  return;
+}
+
+void test_left_tree_constrained_minus(int x, int y, int z) {
+  if (x - y - z != 0)
+return;
+  if (x - y != 0)
+return;
+  clang_analyzer_eval(x - y - z == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x - y == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(z == 0); // expected-warning{{TRUE}}
+  x = y = z = 1;
+  return;
+}
+
+void test_SymInt_constrained(int x, int y, int z) {
+  if (x * y * z != 4)
+return;
+  if (z != 2)
+return;
+  if (x * y == 3) {
+clang_analyzer_warnIfReached(); // no-warning
+return;
+  }
+  (void)(x * y * z);
+}
+
+void test_SValBuilder_simplifies_IntSym(int x, int y, int z) {
+  // Most IntSym BinOps are transformed to SymInt in SimpleSValBuilder.
+  // Division is one exception.
+  x = 77 / (y + z);
+  if (y + z != 1)
+return;
+  clang_analyzer_eval(x == 77); // expected-warning{{TRUE}}
+  (void)(x * y * z);
+}
Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -1102,7 +1102,6 @@
   if (SymbolRef Sym = V.getAsSymbol())
 return state->getConstraintManager().getSymVal(state, Sym);
 
-  // FIXME: Add support for SymExprs.
   return nullptr;
 }
 
@@ -1134,6 +1133,24 @@
   return cache(Sym, SVB.makeSymbolVal(Sym));
 }
 
+// Return the known const value for the Sym if available, or return Undef
+// otherwise.
+SVal getConst(SymbolRef Sym) {
+  const llvm::APSInt *Const =
+  State->getConstraintManager().getSymVal(State, Sym);
+  if (Const)
+return Loc::isLocType(Sym->getType()) ? (SVal)SVB.makeIntLocVal(*Const)
+  : (SVal)SVB.makeIntVal(*Const);
+  return UndefinedVal();
+}
+
+SVal getConstOrVisit(SymbolRef Sym) {
+  const SVal Ret = getConst(Sym);
+  if (Ret.isUndef())
+return Visit(Sym);
+  return Ret;
+}
+
   public:
 Simplifier(ProgramStateRef State)
 : State(State), SVB(State->getStateManager().getSValBuilder()) {}
@@ -1147,15 +1164,14 @@
   

[PATCH] D103317: [Analyzer][Core] Make SValBuilder to better simplify svals with 3 symbols in the tree

2021-11-23 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:1144
+  : (SVal)SVB.makeIntVal(*Const);
+  return SVal();
+}

steakhal wrote:
> Let's be explicit about it.
Good point.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:1148-1151
+  SVal Ret = getConst(Sym);
+  if (Ret.isUndef())
+Ret = Visit(Sym);
+  return Ret;

steakhal wrote:
> 
Makes sense.



Comment at: clang/test/Analysis/svalbuilder-simplify-compound-svals.cpp:23
+  x = y = z = 1;
+  return 0;
+}

steakhal wrote:
> It feels odd that in some of your examples you return some value, but in the 
> rest, you don't.
yep, I agree, updated.



Comment at: clang/test/Analysis/svalbuilder-simplify-compound-svals.cpp:32
+  clang_analyzer_eval(x + y * z == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(y * z == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x == 0); // expected-warning{{TRUE}}

steakhal wrote:
> You could additionally assert that `y == 0` and `z == 0`.
`y * z == 0` does not imply that both `y` and `z` are `0`. However, we could 
expect that one of them is `0`, but currently we don't have such a deduction 
(this might be done in `ConstraintAssignor` in an independent patch).



Comment at: clang/test/Analysis/svalbuilder-simplify-compound-svals.cpp:50
+void test_SymInt_constrained(int x, int y, int z) {
+  if (x * y * z != 4)
+return;

steakhal wrote:
> What if `z` were in the middle? Would it still pass?
No, that would not pass. This is because we do not handle commutativity, for 
that we should have a canonical form of the symbol trees (check out point 3 
here https://reviews.llvm.org/D102696#2784624).



Comment at: clang/test/Analysis/svalbuilder-simplify-compound-svals.cpp:65
+  x = 77 / (y + z);
+  if (y + z != 1)
+return;

steakhal wrote:
> Would the test pass if you were using `z + y != 1` here?
No, because we do not handle commutativity.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103317

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


[PATCH] D103317: [Analyzer][Core] Make SValBuilder to better simplify svals with 3 symbols in the tree

2021-11-23 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

In D103317#3127318 , @steakhal wrote:

> To me at least, the patch looks good.
> Please post some comparative measurements to demonstrate it won't introduce 
> runtime regression.

Sure!

F20586670: stats.html 

Teaser:
F20586689: svalbuilder_improvements.png 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103317

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


[PATCH] D113049: [AIX] Disable tests that fail because of no 64-bit XCOFF object file support

2021-11-23 Thread Jinsong Ji via Phabricator via cfe-commits
jsji added a comment.

Thanks, looks much better now.




Comment at: clang/test/ClangScanDeps/modules-full-by-mod-name.cpp:1
+// UNSUPPORTED: powerpc64-ibm-aix
 // RUN: rm -rf %t.dir

there is no `fmodule-format=obj` here, why are we failing here?




Comment at: clang/test/lit.cfg.py:259
+if 'aix' in config.target_triple:
+for directory in ('/CodeGenCXX', '/Misc', '/Modules', '/PCH'):
+exclude_unsupported_files_for_aix(config.test_source_root + directory)

Why not adding `ASTMerge` and its subfolders?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113049

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


[PATCH] D103317: [Analyzer][Core] Make SValBuilder to better simplify svals with 3 symbols in the tree

2021-11-23 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/test/Analysis/svalbuilder-simplify-compound-svals.cpp:32
+  clang_analyzer_eval(x + y * z == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(y * z == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x == 0); // expected-warning{{TRUE}}

martong wrote:
> steakhal wrote:
> > You could additionally assert that `y == 0` and `z == 0`.
> `y * z == 0` does not imply that both `y` and `z` are `0`. However, we could 
> expect that one of them is `0`, but currently we don't have such a deduction 
> (this might be done in `ConstraintAssignor` in an independent patch).
> this might be done in ConstraintAssignor in an independent patch
Actually, it is not a good idea to bifurcate there (and architecturally 
impossible ATM), so we should implement that differently.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103317

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


[clang] 12887a2 - [Analyzer][Core] Better simplification in SimpleSValBuilder::evalBinOpNN

2021-11-23 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2021-11-23T16:38:01+01:00
New Revision: 12887a202404471ddf77f9fae658700573cbebe8

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

LOG: [Analyzer][Core] Better simplification in SimpleSValBuilder::evalBinOpNN

Make the SValBuilder capable to simplify existing
SVals based on a newly added constraints when evaluating a BinOp.

Before this patch, we called `simplify` only in some edge cases.
However, we can and should investigate the constraints in all cases.

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

Added: 
clang/test/Analysis/svalbuilder-simplify-in-evalbinop.cpp

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

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp 
b/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
index 54a2386fc2ff9..e179ecc33481b 100644
--- a/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ b/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -372,6 +372,15 @@ SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
   NonLoc InputLHS = lhs;
   NonLoc InputRHS = rhs;
 
+  // Constraints may have changed since the creation of a bound SVal. Check if
+  // the values can be simplified based on those new constraints.
+  SVal simplifiedLhs = simplifySVal(state, lhs);
+  SVal simplifiedRhs = simplifySVal(state, rhs);
+  if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs())
+lhs = *simplifiedLhsAsNonLoc;
+  if (auto simplifiedRhsAsNonLoc = simplifiedRhs.getAs())
+rhs = *simplifiedRhsAsNonLoc;
+
   // Handle trivial case where left-side and right-side are the same.
   if (lhs == rhs)
 switch (op) {
@@ -619,16 +628,6 @@ SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
 }
   }
 
-  // Does the symbolic expression simplify to a constant?
-  // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
-  // and try again.
-  SVal simplifiedLhs = simplifySVal(state, lhs);
-  if (simplifiedLhs != lhs)
-if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs()) {
-  lhs = *simplifiedLhsAsNonLoc;
-  continue;
-}
-
   // Is the RHS a constant?
   if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
 return MakeSymIntVal(Sym, op, *RHSValue, resultTy);

diff  --git a/clang/test/Analysis/svalbuilder-simplify-in-evalbinop.cpp 
b/clang/test/Analysis/svalbuilder-simplify-in-evalbinop.cpp
new file mode 100644
index 0..f9a0ee296caf4
--- /dev/null
+++ b/clang/test/Analysis/svalbuilder-simplify-in-evalbinop.cpp
@@ -0,0 +1,30 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+// Here we test whether the SValBuilder is capable to simplify existing
+// SVals based on a newly added constraints when evaluating a BinOp.
+
+void clang_analyzer_eval(bool);
+
+void test_evalBinOp_simplifies_lhs(int y) {
+  int x = y / 77;
+  if (y != 77)
+return;
+
+  // Below `x` is the LHS being simplified.
+  clang_analyzer_eval(x == 1); // expected-warning{{TRUE}}
+  (void)(x * y);
+}
+
+void test_evalBinOp_simplifies_rhs(int y) {
+  int x = y / 77;
+  if (y != 77)
+return;
+
+  // Below `x` is the RHS being simplified.
+  clang_analyzer_eval(1 == x); // expected-warning{{TRUE}}
+  (void)(x * y);
+}



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


[PATCH] D113753: [Analyzer][Core] Better simplification in SimpleSValBuilder::evalBinOpNN

2021-11-23 Thread Gabor Marton 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 rG12887a202404: [Analyzer][Core] Better simplification in 
SimpleSValBuilder::evalBinOpNN (authored by martong).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113753

Files:
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/test/Analysis/svalbuilder-simplify-in-evalbinop.cpp


Index: clang/test/Analysis/svalbuilder-simplify-in-evalbinop.cpp
===
--- /dev/null
+++ clang/test/Analysis/svalbuilder-simplify-in-evalbinop.cpp
@@ -0,0 +1,30 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+// Here we test whether the SValBuilder is capable to simplify existing
+// SVals based on a newly added constraints when evaluating a BinOp.
+
+void clang_analyzer_eval(bool);
+
+void test_evalBinOp_simplifies_lhs(int y) {
+  int x = y / 77;
+  if (y != 77)
+return;
+
+  // Below `x` is the LHS being simplified.
+  clang_analyzer_eval(x == 1); // expected-warning{{TRUE}}
+  (void)(x * y);
+}
+
+void test_evalBinOp_simplifies_rhs(int y) {
+  int x = y / 77;
+  if (y != 77)
+return;
+
+  // Below `x` is the RHS being simplified.
+  clang_analyzer_eval(1 == x); // expected-warning{{TRUE}}
+  (void)(x * y);
+}
Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -372,6 +372,15 @@
   NonLoc InputLHS = lhs;
   NonLoc InputRHS = rhs;
 
+  // Constraints may have changed since the creation of a bound SVal. Check if
+  // the values can be simplified based on those new constraints.
+  SVal simplifiedLhs = simplifySVal(state, lhs);
+  SVal simplifiedRhs = simplifySVal(state, rhs);
+  if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs())
+lhs = *simplifiedLhsAsNonLoc;
+  if (auto simplifiedRhsAsNonLoc = simplifiedRhs.getAs())
+rhs = *simplifiedRhsAsNonLoc;
+
   // Handle trivial case where left-side and right-side are the same.
   if (lhs == rhs)
 switch (op) {
@@ -619,16 +628,6 @@
 }
   }
 
-  // Does the symbolic expression simplify to a constant?
-  // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
-  // and try again.
-  SVal simplifiedLhs = simplifySVal(state, lhs);
-  if (simplifiedLhs != lhs)
-if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs()) {
-  lhs = *simplifiedLhsAsNonLoc;
-  continue;
-}
-
   // Is the RHS a constant?
   if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
 return MakeSymIntVal(Sym, op, *RHSValue, resultTy);


Index: clang/test/Analysis/svalbuilder-simplify-in-evalbinop.cpp
===
--- /dev/null
+++ clang/test/Analysis/svalbuilder-simplify-in-evalbinop.cpp
@@ -0,0 +1,30 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+// Here we test whether the SValBuilder is capable to simplify existing
+// SVals based on a newly added constraints when evaluating a BinOp.
+
+void clang_analyzer_eval(bool);
+
+void test_evalBinOp_simplifies_lhs(int y) {
+  int x = y / 77;
+  if (y != 77)
+return;
+
+  // Below `x` is the LHS being simplified.
+  clang_analyzer_eval(x == 1); // expected-warning{{TRUE}}
+  (void)(x * y);
+}
+
+void test_evalBinOp_simplifies_rhs(int y) {
+  int x = y / 77;
+  if (y != 77)
+return;
+
+  // Below `x` is the RHS being simplified.
+  clang_analyzer_eval(1 == x); // expected-warning{{TRUE}}
+  (void)(x * y);
+}
Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -372,6 +372,15 @@
   NonLoc InputLHS = lhs;
   NonLoc InputRHS = rhs;
 
+  // Constraints may have changed since the creation of a bound SVal. Check if
+  // the values can be simplified based on those new constraints.
+  SVal simplifiedLhs = simplifySVal(state, lhs);
+  SVal simplifiedRhs = simplifySVal(state, rhs);
+  if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs())
+lhs = *simplifiedLhsAsNonLoc;
+  if (auto simplifiedRhsAsNonLoc = simplifiedRhs.getAs())
+rhs = *simplifiedRhsAsNonLoc;
+
   // Handle trivial case where left-side and right-side are the same.
   if (lhs == rhs)
 switch (op) {
@@ -619,16 +628,6 @@
 }
   }
 
-  // Does the symbolic ex

[PATCH] D113753: [Analyzer][Core] Better simplification in SimpleSValBuilder::evalBinOpNN

2021-11-23 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

I'm attaching the coverage of the new test file for the related change:

  375 :   // Constraints may have changed since the creation of a 
bound SVal. Check if
  376 :   // the values can be simplified based on those new 
constraints.
  377  12 :   SVal simplifiedLhs = simplifySVal(state, lhs);
  378  12 :   SVal simplifiedRhs = simplifySVal(state, rhs);
  379  12 :   if (auto simplifiedLhsAsNonLoc = 
simplifiedLhs.getAs())
  380  12 : lhs = *simplifiedLhsAsNonLoc;
  381  12 :   if (auto simplifiedRhsAsNonLoc = 
simplifiedRhs.getAs())
  382  12 : rhs = *simplifiedRhsAsNonLoc;
  383 :


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113753

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


[clang] aa9b90c - Fix warning due to default switch label

2021-11-23 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2021-11-23T10:52:51-05:00
New Revision: aa9b90ca441d09969cab158f1db6341de3c1

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

LOG: Fix warning due to default switch label

Fix warning due to default label in switch which covers all enumeration values

Added: 


Modified: 
clang/lib/CodeGen/TargetInfo.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/TargetInfo.cpp 
b/clang/lib/CodeGen/TargetInfo.cpp
index 824a458e8b53d..4360269f8af19 100644
--- a/clang/lib/CodeGen/TargetInfo.cpp
+++ b/clang/lib/CodeGen/TargetInfo.cpp
@@ -9358,9 +9358,6 @@ AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const 
LangOptions &LangOpts,
   case SyncScope::OpenCLAllSVMDevices:
 Name = "";
 break;
-  default:
-assert(false && "NOT IMPLEMENTED");
-break;
   }
 
   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {



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


[PATCH] D103317: [Analyzer][Core] Make SValBuilder to better simplify svals with 3 symbols in the tree

2021-11-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D103317#3148868 , @martong wrote:

> In D103317#3127318 , @steakhal 
> wrote:
>
>> To me at least, the patch looks good.
>> Please post some comparative measurements to demonstrate it won't introduce 
>> runtime regression.
>
> Sure!
>
> F20586670: stats.html 
>
> Teaser:
> F20586689: svalbuilder_improvements.png 

Please repeat the measurement for `openssl`. There must have been some 
interference in the memory consumption. Aside from that the results look great.




Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:1105
 
-  // FIXME: Add support for SymExprs.
   return nullptr;

Where did you address this FIXME?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103317

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


[PATCH] D114418: [clang][ASTImporter] Update lookup table correctly at deduction guides.

2021-11-23 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/AST/ASTImporter.cpp:6081
+  // FunctionTemplateDecl objects are created, but in different order. In this
+  // way DeclContext of these template parameters may change relative to the
+  // "from" context. Because these DeclContext values look already not stable

?



Comment at: clang/lib/AST/ASTImporter.cpp:6082-6085
+  // "from" context. Because these DeclContext values look already not stable
+  // and unimportant this change looks acceptable.
+  // For these reasons the old DeclContext must be saved to change the lookup
+  // table later.

I think this sentence does not provide any meaningful information and does not 
increase the understand-ability. Plus the word `change` is overloaded, first I 
though you meant the patch itself...



Comment at: clang/unittests/AST/ASTImporterTest.cpp:7336
+
+TEST_P(ASTImporterOptionSpecificTestBase, ImportDeductionGuide) {
+  TranslationUnitDecl *FromTU = getTuDecl(

Does this test provide an assertion failure in the base?



Comment at: clang/unittests/AST/ASTImporterTest.cpp:7348-7353
+  // Get the implicit deduction guide for (non-default) constructor of 'B'.
+  auto *FromDG1 = FirstDeclMatcher().match(
+  FromTU, functionTemplateDecl(templateParameterCountIs(3)));
+  // User defined deduction guide.
+  auto *FromDG2 = FirstDeclMatcher().match(
+  FromTU, cxxDeductionGuideDecl(unless(isImplicit(;

Could you please formulate expectations (assertions) on the DeclContext's of 
the two template parameters? I'd expect them to be different.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114418

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


[PATCH] D113118: [clang][AST] Check context of record in structural equivalence.

2021-11-23 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.

Still LGTM! Let's land it!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113118

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


[clang] b472bd8 - [NFC] Let Microsoft mangler accept GlobalDecl

2021-11-23 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2021-11-23T10:59:26-05:00
New Revision: b472bd855ed85691d0d03ef1808c82b780d23721

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

LOG: [NFC] Let Microsoft mangler accept GlobalDecl

This is a follow up of https://reviews.llvm.org/D75700
where support of GlobalDecl with Microsoft mangler
is incomplete.

Reviewed by: Artem Belevich, Reid Kleckner

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

Added: 


Modified: 
clang/lib/AST/MicrosoftMangle.cpp

Removed: 




diff  --git a/clang/lib/AST/MicrosoftMangle.cpp 
b/clang/lib/AST/MicrosoftMangle.cpp
index 163d4e95386e..beca1be78d99 100644
--- a/clang/lib/AST/MicrosoftMangle.cpp
+++ b/clang/lib/AST/MicrosoftMangle.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/GlobalDecl.h"
 #include "clang/AST/Mangle.h"
 #include "clang/AST/VTableBuilder.h"
 #include "clang/Basic/ABI.h"
@@ -39,6 +40,18 @@ using namespace clang;
 
 namespace {
 
+// Get GlobalDecl of DeclContext of local entities.
+static GlobalDecl getGlobalDeclAsDeclContext(const DeclContext *DC) {
+  GlobalDecl GD;
+  if (auto *CD = dyn_cast(DC))
+GD = GlobalDecl(CD, Ctor_Complete);
+  else if (auto *DD = dyn_cast(DC))
+GD = GlobalDecl(DD, Dtor_Complete);
+  else
+GD = GlobalDecl(cast(DC));
+  return GD;
+}
+
 struct msvc_hashing_ostream : public llvm::raw_svector_ostream {
   raw_ostream &OS;
   llvm::SmallString<64> Buffer;
@@ -345,9 +358,9 @@ class MicrosoftCXXNameMangler {
 
   raw_ostream &getStream() const { return Out; }
 
-  void mangle(const NamedDecl *D, StringRef Prefix = "?");
-  void mangleName(const NamedDecl *ND);
-  void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle);
+  void mangle(GlobalDecl GD, StringRef Prefix = "?");
+  void mangleName(GlobalDecl GD);
+  void mangleFunctionEncoding(GlobalDecl GD, bool ShouldMangle);
   void mangleVariableEncoding(const VarDecl *VD);
   void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD,
StringRef Prefix = "$");
@@ -370,7 +383,7 @@ class MicrosoftCXXNameMangler {
   const FunctionDecl *D = nullptr,
   bool ForceThisQuals = false,
   bool MangleExceptionSpec = true);
-  void mangleNestedName(const NamedDecl *ND);
+  void mangleNestedName(GlobalDecl GD);
 
 private:
   bool isStructorDecl(const NamedDecl *ND) const {
@@ -384,10 +397,10 @@ class MicrosoftCXXNameMangler {
   AddrSpace == LangAS::ptr32_uptr));
   }
 
-  void mangleUnqualifiedName(const NamedDecl *ND) {
-mangleUnqualifiedName(ND, ND->getDeclName());
+  void mangleUnqualifiedName(GlobalDecl GD) {
+mangleUnqualifiedName(GD, cast(GD.getDecl())->getDeclName());
   }
-  void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
+  void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name);
   void mangleSourceName(StringRef Name);
   void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
   void mangleCXXDtorType(CXXDtorType T);
@@ -396,9 +409,9 @@ class MicrosoftCXXNameMangler {
   void manglePointerCVQualifiers(Qualifiers Quals);
   void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
 
-  void mangleUnscopedTemplateName(const TemplateDecl *ND);
+  void mangleUnscopedTemplateName(GlobalDecl GD);
   void
-  mangleTemplateInstantiationName(const TemplateDecl *TD,
+  mangleTemplateInstantiationName(GlobalDecl GD,
   const TemplateArgumentList &TemplateArgs);
   void mangleObjCMethodName(const ObjCMethodDecl *MD);
 
@@ -533,7 +546,8 @@ MicrosoftMangleContextImpl::shouldMangleStringLiteral(const 
StringLiteral *SL) {
   return true;
 }
 
-void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
+void MicrosoftCXXNameMangler::mangle(GlobalDecl GD, StringRef Prefix) {
+  const NamedDecl *D = cast(GD.getDecl());
   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
   // Therefore it's really important that we don't decorate the
   // name with leading underscores or leading/trailing at signs. So, by
@@ -542,9 +556,9 @@ void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, 
StringRef Prefix) {
 
   //  ::= ?  
   Out << Prefix;
-  mangleName(D);
+  mangleName(GD);
   if (const FunctionDecl *FD = dyn_cast(D))
-mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD));
+mangleFunctionEncoding(GD, Context.shouldMangleDeclName(FD));
   else if (const VarDecl *VD = dyn_cast(D))
 mangleVariableEncoding(VD);
   else if (isa(D))
@@ -558,8 +572,9 @@ void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, 
StringRef

[PATCH] D113490: [NFC] Let Microsoft mangler accept GlobalDecl

2021-11-23 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
yaxunl marked an inline comment as done.
Closed by commit rGb472bd855ed8: [NFC] Let Microsoft mangler accept GlobalDecl 
(authored by yaxunl).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D113490?vs=385834&id=389217#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113490

Files:
  clang/lib/AST/MicrosoftMangle.cpp

Index: clang/lib/AST/MicrosoftMangle.cpp
===
--- clang/lib/AST/MicrosoftMangle.cpp
+++ clang/lib/AST/MicrosoftMangle.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/GlobalDecl.h"
 #include "clang/AST/Mangle.h"
 #include "clang/AST/VTableBuilder.h"
 #include "clang/Basic/ABI.h"
@@ -39,6 +40,18 @@
 
 namespace {
 
+// Get GlobalDecl of DeclContext of local entities.
+static GlobalDecl getGlobalDeclAsDeclContext(const DeclContext *DC) {
+  GlobalDecl GD;
+  if (auto *CD = dyn_cast(DC))
+GD = GlobalDecl(CD, Ctor_Complete);
+  else if (auto *DD = dyn_cast(DC))
+GD = GlobalDecl(DD, Dtor_Complete);
+  else
+GD = GlobalDecl(cast(DC));
+  return GD;
+}
+
 struct msvc_hashing_ostream : public llvm::raw_svector_ostream {
   raw_ostream &OS;
   llvm::SmallString<64> Buffer;
@@ -345,9 +358,9 @@
 
   raw_ostream &getStream() const { return Out; }
 
-  void mangle(const NamedDecl *D, StringRef Prefix = "?");
-  void mangleName(const NamedDecl *ND);
-  void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle);
+  void mangle(GlobalDecl GD, StringRef Prefix = "?");
+  void mangleName(GlobalDecl GD);
+  void mangleFunctionEncoding(GlobalDecl GD, bool ShouldMangle);
   void mangleVariableEncoding(const VarDecl *VD);
   void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD,
StringRef Prefix = "$");
@@ -370,7 +383,7 @@
   const FunctionDecl *D = nullptr,
   bool ForceThisQuals = false,
   bool MangleExceptionSpec = true);
-  void mangleNestedName(const NamedDecl *ND);
+  void mangleNestedName(GlobalDecl GD);
 
 private:
   bool isStructorDecl(const NamedDecl *ND) const {
@@ -384,10 +397,10 @@
   AddrSpace == LangAS::ptr32_uptr));
   }
 
-  void mangleUnqualifiedName(const NamedDecl *ND) {
-mangleUnqualifiedName(ND, ND->getDeclName());
+  void mangleUnqualifiedName(GlobalDecl GD) {
+mangleUnqualifiedName(GD, cast(GD.getDecl())->getDeclName());
   }
-  void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
+  void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name);
   void mangleSourceName(StringRef Name);
   void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
   void mangleCXXDtorType(CXXDtorType T);
@@ -396,9 +409,9 @@
   void manglePointerCVQualifiers(Qualifiers Quals);
   void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
 
-  void mangleUnscopedTemplateName(const TemplateDecl *ND);
+  void mangleUnscopedTemplateName(GlobalDecl GD);
   void
-  mangleTemplateInstantiationName(const TemplateDecl *TD,
+  mangleTemplateInstantiationName(GlobalDecl GD,
   const TemplateArgumentList &TemplateArgs);
   void mangleObjCMethodName(const ObjCMethodDecl *MD);
 
@@ -533,7 +546,8 @@
   return true;
 }
 
-void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
+void MicrosoftCXXNameMangler::mangle(GlobalDecl GD, StringRef Prefix) {
+  const NamedDecl *D = cast(GD.getDecl());
   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
   // Therefore it's really important that we don't decorate the
   // name with leading underscores or leading/trailing at signs. So, by
@@ -542,9 +556,9 @@
 
   //  ::= ?  
   Out << Prefix;
-  mangleName(D);
+  mangleName(GD);
   if (const FunctionDecl *FD = dyn_cast(D))
-mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD));
+mangleFunctionEncoding(GD, Context.shouldMangleDeclName(FD));
   else if (const VarDecl *VD = dyn_cast(D))
 mangleVariableEncoding(VD);
   else if (isa(D))
@@ -558,8 +572,9 @@
 llvm_unreachable("Tried to mangle unexpected NamedDecl!");
 }
 
-void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD,
+void MicrosoftCXXNameMangler::mangleFunctionEncoding(GlobalDecl GD,
  bool ShouldMangle) {
+  const FunctionDecl *FD = cast(GD.getDecl());
   //  ::=  
 
   // Since MSVC operates on the type as written and not the canonical type, it
@@ -770,13 +785,13 @@
   mangleCallingConvention(MD->getType()->castAs());
 }
 
-void MicrosoftCXXNameMangler::mangleName(const N

[PATCH] D103317: [Analyzer][Core] Make SValBuilder to better simplify svals with 3 symbols in the tree

2021-11-23 Thread Gabor Marton via Phabricator via cfe-commits
martong marked an inline comment as done.
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:1105
 
-  // FIXME: Add support for SymExprs.
   return nullptr;

steakhal wrote:
> Where did you address this FIXME?
I didn't, but this `FIXME` became obsolete at some point in the past. 

The reasons:
1) We do support `SymExprs`. In `simplifySVal` we have a full blown SymExpr 
visitor implemented that checks for constant values in the symbol subtrees. And 
at L1103 we query the top symbol of tree as well.

2) The git history shows that the FIXME was previously this: `// FIXME: Add 
support for SymExprs in RangeConstraintManager.` But we do support SymExprs 
already in RangeConstraintManager ...



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103317

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


[PATCH] D114446: [clang] Fix wrong -Wunused-local-typedef warning if use is a dependent qialified identifier

2021-11-23 Thread Kristina Bessonova via Phabricator via cfe-commits
krisb created this revision.
krisb added reviewers: thakis, rtrieu, rsmith.
krisb requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Attempt to fix Tom Smeding's example from 
https://bugs.llvm.org/show_bug.cgi?id=24883.

Given the case like this one:

  struct A {
void f() const {}
  };
  
  template 
  void handler(const T &item) {
using a_type_t = A;
item.a_type_t::f();
  }
  
  int main() {
handler(A());
  }

there is no way to know whether the typedef is used or not before
the templated context is instantiated.

Having this the patch proposes deffering all the diagnostics for
typedefs defined within a dependent context.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114446

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/SemaCXX/warn-unused-local-typedef.cpp


Index: clang/test/SemaCXX/warn-unused-local-typedef.cpp
===
--- clang/test/SemaCXX/warn-unused-local-typedef.cpp
+++ clang/test/SemaCXX/warn-unused-local-typedef.cpp
@@ -255,5 +255,20 @@
 }
 } // TypedefInLocalClassOfTemplateClassMember
 
+namespace TypedefInDependentQualifiedIdentifier {
+struct A { void f() const {} };
+
+template 
+void handler(const T &item) {
+   using a_type_t = A; // no-diag
+  using b_type_t = A; // expected-warning {{unused type alias 'b_type_t'}}
+   item.a_type_t::f();
+}
+
+void foo() {
+   handler(A());
+}
+} // TypedefInDependentQualifiedIdentifier
+
 // This should not disable any warnings:
 #pragma clang diagnostic ignored "-Wunused-local-typedef"
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -955,6 +955,14 @@
   Typedef->setAccess(D->getAccess());
   Typedef->setReferenced(D->isReferenced());
 
+  // Diagnose unused local typedefs here since diagnostics for typedefs
+  // in a dependent context were deffered).
+  bool ShouldDiagnoseUnused = Typedef->getDeclContext()->isFunctionOrMethod();
+  if (const auto *R = dyn_cast(Typedef->getDeclContext()))
+ShouldDiagnoseUnused = ShouldDiagnoseUnused || R->isLocalClass();
+  if (!Typedef->isInvalidDecl() && ShouldDiagnoseUnused)
+SemaRef.DiagnoseUnusedDecl(Typedef);
+
   return Typedef;
 }
 
@@ -1907,8 +1915,6 @@
 LocalInstantiations.perform();
   }
 
-  SemaRef.DiagnoseUnusedNestedTypedefs(Record);
-
   if (IsInjectedClassName)
 assert(Record->isInjectedClassName() && "Broken injected-class-name");
 
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -1794,16 +1794,19 @@
 
   // Except for labels, we only care about unused decls that are local to
   // functions.
-  bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
-  if (const auto *R = dyn_cast(D->getDeclContext()))
-// For dependent types, the diagnostic is deferred.
-WithinFunction =
-WithinFunction || (R->isLocalClass() && !R->isDependentType());
+  auto *Context = D->getDeclContext();
+  bool WithinFunction = Context->isFunctionOrMethod();
+  if (const auto *R = dyn_cast(Context))
+WithinFunction = WithinFunction || R->isLocalClass();
   if (!WithinFunction)
 return false;
 
-  if (isa(D))
+  if (const auto *TD = dyn_cast(D)) {
+// Defer warnings for typedefs within a dependent context.
+if (Context->isDependentContext())
+  return false;
 return true;
+  }
 
   // White-list anything that isn't a local variable.
   if (!isa(D) || isa(D) || isa(D))


Index: clang/test/SemaCXX/warn-unused-local-typedef.cpp
===
--- clang/test/SemaCXX/warn-unused-local-typedef.cpp
+++ clang/test/SemaCXX/warn-unused-local-typedef.cpp
@@ -255,5 +255,20 @@
 }
 } // TypedefInLocalClassOfTemplateClassMember
 
+namespace TypedefInDependentQualifiedIdentifier {
+struct A { void f() const {} };
+
+template 
+void handler(const T &item) {
+	using a_type_t = A; // no-diag
+  using b_type_t = A; // expected-warning {{unused type alias 'b_type_t'}}
+	item.a_type_t::f();
+}
+
+void foo() {
+	handler(A());
+}
+} // TypedefInDependentQualifiedIdentifier
+
 // This should not disable any warnings:
 #pragma clang diagnostic ignored "-Wunused-local-typedef"
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -955,6 +955,14 @@
   Typedef->setAccess(D->getAccess());
   Typedef->setReferenced(D->isReferenced());
 
+  // Diagnose unused local typedefs here since diagnostics for typedefs
+  // in a dependent context were deffered).
+  bool Sho

[PATCH] D114256: [clang-tidy] Fix crashing altera-struct-pack-align on invalid RecordDecls

2021-11-23 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

What happens if this checker runs on a forward declared class?

  struct Foo;

I'd expect the pack/alignment info is missing also in that case.




Comment at: clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp:54
 
+  // Ignore invalid decls to prevent crashing on calling `getASTRecordLayout`.
+  if (Struct->isInvalidDecl())

I'd mention first that packing and alignment info are meaningless for invalid 
declarations.


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

https://reviews.llvm.org/D114256

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


[PATCH] D103317: [Analyzer][Core] Make SValBuilder to better simplify svals with 3 symbols in the tree

2021-11-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:1105
 
-  // FIXME: Add support for SymExprs.
   return nullptr;

martong wrote:
> steakhal wrote:
> > Where did you address this FIXME?
> I didn't, but this `FIXME` became obsolete at some point in the past. 
> 
> The reasons:
> 1) We do support `SymExprs`. In `simplifySVal` we have a full blown SymExpr 
> visitor implemented that checks for constant values in the symbol subtrees. 
> And at L1103 we query the top symbol of tree as well.
> 
> 2) The git history shows that the FIXME was previously this: `// FIXME: Add 
> support for SymExprs in RangeConstraintManager.` But we do support SymExprs 
> already in RangeConstraintManager ...
> 
Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103317

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


[PATCH] D114256: [clang-tidy] Fix crashing altera-struct-pack-align on invalid RecordDecls

2021-11-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 389225.
steakhal marked an inline comment as done.
steakhal added a comment.

- update comments
- move `no-crash` comment inline to the class member declaration


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

https://reviews.llvm.org/D114256

Files:
  clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align-invalid-decl-no-crash.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align-invalid-decl-no-crash.cpp
===
--- /dev/null
+++ 
clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align-invalid-decl-no-crash.cpp
@@ -0,0 +1,6 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s altera-struct-pack-align 
%t -- -header-filter=.*
+
+struct Foo {
+  member; // no-crash
+};
+// CHECK-MESSAGES: :[[@LINE-2]]:3: error: C++ requires a type specifier for 
all declarations [clang-diagnostic-error]
Index: clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
===
--- clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
+++ clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
@@ -51,6 +51,10 @@
   if (Struct->isTemplated())
  return;
 
+  // Packing and alignment requirements for invalid decls are meaningless.
+  if (Struct->isInvalidDecl())
+return;
+
   // Get sizing info for the struct.
   llvm::SmallVector, 10> FieldSizes;
   unsigned int TotalBitSize = 0;


Index: clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align-invalid-decl-no-crash.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align-invalid-decl-no-crash.cpp
@@ -0,0 +1,6 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s altera-struct-pack-align %t -- -header-filter=.*
+
+struct Foo {
+  member; // no-crash
+};
+// CHECK-MESSAGES: :[[@LINE-2]]:3: error: C++ requires a type specifier for all declarations [clang-diagnostic-error]
Index: clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
===
--- clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
+++ clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
@@ -51,6 +51,10 @@
   if (Struct->isTemplated())
  return;
 
+  // Packing and alignment requirements for invalid decls are meaningless.
+  if (Struct->isInvalidDecl())
+return;
+
   // Get sizing info for the struct.
   llvm::SmallVector, 10> FieldSizes;
   unsigned int TotalBitSize = 0;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D114256: [clang-tidy] Fix crashing altera-struct-pack-align on invalid RecordDecls

2021-11-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D114256#3149009 , @martong wrote:

> What happens if this checker runs on a forward declared class?

The matcher `recordDecl(isStruct(), **isDefinition()**, 
unless(isExpansionInSystemHeader()))` filters that case.

Thanks for the review @martong!




Comment at: clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp:54
 
+  // Ignore invalid decls to prevent crashing on calling `getASTRecordLayout`.
+  if (Struct->isInvalidDecl())

martong wrote:
> I'd mention first that packing and alignment info are meaningless for invalid 
> declarations.
Makes sense.


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

https://reviews.llvm.org/D114256

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


[clang] 38211bb - [HIP] Fix device stub name for Windows

2021-11-23 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2021-11-23T12:03:49-05:00
New Revision: 38211bbab1d949f682271abba0171424a5a335ab

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

LOG: [HIP] Fix device stub name for Windows

This is a follow up of https://reviews.llvm.org/D68578
where device stub name is changed for Itanium
mangling but not Microsoft mangling.

Reviewed by: Artem Belevich

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

Added: 


Modified: 
clang/include/clang/AST/GlobalDecl.h
clang/lib/AST/MicrosoftMangle.cpp
clang/test/CodeGenCUDA/kernel-stub-name.cu

Removed: 




diff  --git a/clang/include/clang/AST/GlobalDecl.h 
b/clang/include/clang/AST/GlobalDecl.h
index 8cb56fb4ae90b..88abba28c991d 100644
--- a/clang/include/clang/AST/GlobalDecl.h
+++ b/clang/include/clang/AST/GlobalDecl.h
@@ -18,6 +18,7 @@
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DeclOpenMP.h"
+#include "clang/AST/DeclTemplate.h"
 #include "clang/Basic/ABI.h"
 #include "clang/Basic/LLVM.h"
 #include "llvm/ADT/DenseMapInfo.h"
@@ -129,8 +130,12 @@ class GlobalDecl {
   }
 
   KernelReferenceKind getKernelReferenceKind() const {
-assert(isa(getDecl()) &&
-   cast(getDecl())->hasAttr() &&
+assert(((isa(getDecl()) &&
+ cast(getDecl())->hasAttr()) ||
+(isa(getDecl()) &&
+ cast(getDecl())
+ ->getTemplatedDecl()
+ ->hasAttr())) &&
"Decl is not a GPU kernel!");
 return static_cast(Value.getInt());
   }

diff  --git a/clang/lib/AST/MicrosoftMangle.cpp 
b/clang/lib/AST/MicrosoftMangle.cpp
index beca1be78d99e..79a448a2435cd 100644
--- a/clang/lib/AST/MicrosoftMangle.cpp
+++ b/clang/lib/AST/MicrosoftMangle.cpp
@@ -962,7 +962,19 @@ void 
MicrosoftCXXNameMangler::mangleUnqualifiedName(GlobalDecl GD,
   switch (Name.getNameKind()) {
 case DeclarationName::Identifier: {
   if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
-mangleSourceName(II->getName());
+bool IsDeviceStub =
+ND &&
+((isa(ND) && ND->hasAttr()) ||
+ (isa(ND) &&
+  cast(ND)
+  ->getTemplatedDecl()
+  ->hasAttr())) &&
+GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
+if (IsDeviceStub)
+  mangleSourceName(
+  (llvm::Twine("__device_stub__") + II->getName()).str());
+else
+  mangleSourceName(II->getName());
 break;
   }
 

diff  --git a/clang/test/CodeGenCUDA/kernel-stub-name.cu 
b/clang/test/CodeGenCUDA/kernel-stub-name.cu
index 8e82c3612e323..71856bee98902 100644
--- a/clang/test/CodeGenCUDA/kernel-stub-name.cu
+++ b/clang/test/CodeGenCUDA/kernel-stub-name.cu
@@ -28,8 +28,8 @@
 // GNU: @[[HDKERN:_Z11kernel_declv]] = external constant void ()*, align 8
 
 // MSVC: @[[HCKERN:ckernel]] = dso_local constant void ()* 
@[[CSTUB:__device_stub__ckernel]], align 8
-// MSVC: @[[HNSKERN:"\?nskernel@ns@@YAXXZ.*"]] = dso_local constant void ()* 
@[[NSSTUB:"\?nskernel@ns@@YAXXZ"]], align 8
-// MSVC: @[[HTKERN:"\?\?\$kernelfunc@H@@YAXXZ.*"]] = linkonce_odr dso_local 
constant void ()* @[[TSTUB:"\?\?\$kernelfunc@H@@YAXXZ.*"]], comdat, align 8
+// MSVC: @[[HNSKERN:"\?nskernel@ns@@YAXXZ.*"]] = dso_local constant void ()* 
@[[NSSTUB:"\?__device_stub__nskernel@ns@@YAXXZ"]], align 8
+// MSVC: @[[HTKERN:"\?\?\$kernelfunc@H@@YAXXZ.*"]] = linkonce_odr dso_local 
constant void ()* @[[TSTUB:"\?\?\$__device_stub__kernelfunc@H@@YAXXZ.*"]], 
comdat, align 8
 // MSVC: @[[HDKERN:"\?kernel_decl@@YAXXZ.*"]] = external dso_local constant 
void ()*, align 8
 
 extern "C" __global__ void ckernel() {}
@@ -69,7 +69,7 @@ extern "C" void launch(void *kern);
 // CHECK: call void @[[NSSTUB]]()
 // CHECK: call void @[[TSTUB]]()
 // GNU: call void @[[DSTUB:_Z26__device_stub__kernel_declv]]()
-// MSVC: call void @[[DSTUB:"\?kernel_decl@@YAXXZ"]]()
+// MSVC: call void @[[DSTUB:"\?__device_stub__kernel_decl@@YAXXZ"]]()
 
 extern "C" void fun1(void) {
   ckernel<<<1, 1>>>();



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


[PATCH] D113491: [HIP] Fix device stub name for Windows

2021-11-23 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
yaxunl marked an inline comment as done.
Closed by commit rG38211bbab1d9: [HIP] Fix device stub name for Windows 
(authored by yaxunl).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D113491?vs=385836&id=389228#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113491

Files:
  clang/include/clang/AST/GlobalDecl.h
  clang/lib/AST/MicrosoftMangle.cpp
  clang/test/CodeGenCUDA/kernel-stub-name.cu


Index: clang/test/CodeGenCUDA/kernel-stub-name.cu
===
--- clang/test/CodeGenCUDA/kernel-stub-name.cu
+++ clang/test/CodeGenCUDA/kernel-stub-name.cu
@@ -28,8 +28,8 @@
 // GNU: @[[HDKERN:_Z11kernel_declv]] = external constant void ()*, align 8
 
 // MSVC: @[[HCKERN:ckernel]] = dso_local constant void ()* 
@[[CSTUB:__device_stub__ckernel]], align 8
-// MSVC: @[[HNSKERN:"\?nskernel@ns@@YAXXZ.*"]] = dso_local constant void ()* 
@[[NSSTUB:"\?nskernel@ns@@YAXXZ"]], align 8
-// MSVC: @[[HTKERN:"\?\?\$kernelfunc@H@@YAXXZ.*"]] = linkonce_odr dso_local 
constant void ()* @[[TSTUB:"\?\?\$kernelfunc@H@@YAXXZ.*"]], comdat, align 8
+// MSVC: @[[HNSKERN:"\?nskernel@ns@@YAXXZ.*"]] = dso_local constant void ()* 
@[[NSSTUB:"\?__device_stub__nskernel@ns@@YAXXZ"]], align 8
+// MSVC: @[[HTKERN:"\?\?\$kernelfunc@H@@YAXXZ.*"]] = linkonce_odr dso_local 
constant void ()* @[[TSTUB:"\?\?\$__device_stub__kernelfunc@H@@YAXXZ.*"]], 
comdat, align 8
 // MSVC: @[[HDKERN:"\?kernel_decl@@YAXXZ.*"]] = external dso_local constant 
void ()*, align 8
 
 extern "C" __global__ void ckernel() {}
@@ -69,7 +69,7 @@
 // CHECK: call void @[[NSSTUB]]()
 // CHECK: call void @[[TSTUB]]()
 // GNU: call void @[[DSTUB:_Z26__device_stub__kernel_declv]]()
-// MSVC: call void @[[DSTUB:"\?kernel_decl@@YAXXZ"]]()
+// MSVC: call void @[[DSTUB:"\?__device_stub__kernel_decl@@YAXXZ"]]()
 
 extern "C" void fun1(void) {
   ckernel<<<1, 1>>>();
Index: clang/lib/AST/MicrosoftMangle.cpp
===
--- clang/lib/AST/MicrosoftMangle.cpp
+++ clang/lib/AST/MicrosoftMangle.cpp
@@ -962,7 +962,19 @@
   switch (Name.getNameKind()) {
 case DeclarationName::Identifier: {
   if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
-mangleSourceName(II->getName());
+bool IsDeviceStub =
+ND &&
+((isa(ND) && ND->hasAttr()) ||
+ (isa(ND) &&
+  cast(ND)
+  ->getTemplatedDecl()
+  ->hasAttr())) &&
+GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
+if (IsDeviceStub)
+  mangleSourceName(
+  (llvm::Twine("__device_stub__") + II->getName()).str());
+else
+  mangleSourceName(II->getName());
 break;
   }
 
Index: clang/include/clang/AST/GlobalDecl.h
===
--- clang/include/clang/AST/GlobalDecl.h
+++ clang/include/clang/AST/GlobalDecl.h
@@ -18,6 +18,7 @@
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DeclOpenMP.h"
+#include "clang/AST/DeclTemplate.h"
 #include "clang/Basic/ABI.h"
 #include "clang/Basic/LLVM.h"
 #include "llvm/ADT/DenseMapInfo.h"
@@ -129,8 +130,12 @@
   }
 
   KernelReferenceKind getKernelReferenceKind() const {
-assert(isa(getDecl()) &&
-   cast(getDecl())->hasAttr() &&
+assert(((isa(getDecl()) &&
+ cast(getDecl())->hasAttr()) ||
+(isa(getDecl()) &&
+ cast(getDecl())
+ ->getTemplatedDecl()
+ ->hasAttr())) &&
"Decl is not a GPU kernel!");
 return static_cast(Value.getInt());
   }


Index: clang/test/CodeGenCUDA/kernel-stub-name.cu
===
--- clang/test/CodeGenCUDA/kernel-stub-name.cu
+++ clang/test/CodeGenCUDA/kernel-stub-name.cu
@@ -28,8 +28,8 @@
 // GNU: @[[HDKERN:_Z11kernel_declv]] = external constant void ()*, align 8
 
 // MSVC: @[[HCKERN:ckernel]] = dso_local constant void ()* @[[CSTUB:__device_stub__ckernel]], align 8
-// MSVC: @[[HNSKERN:"\?nskernel@ns@@YAXXZ.*"]] = dso_local constant void ()* @[[NSSTUB:"\?nskernel@ns@@YAXXZ"]], align 8
-// MSVC: @[[HTKERN:"\?\?\$kernelfunc@H@@YAXXZ.*"]] = linkonce_odr dso_local constant void ()* @[[TSTUB:"\?\?\$kernelfunc@H@@YAXXZ.*"]], comdat, align 8
+// MSVC: @[[HNSKERN:"\?nskernel@ns@@YAXXZ.*"]] = dso_local constant void ()* @[[NSSTUB:"\?__device_stub__nskernel@ns@@YAXXZ"]], align 8
+// MSVC: @[[HTKERN:"\?\?\$kernelfunc@H@@YAXXZ.*"]] = linkonce_odr dso_local constant void ()* @[[TSTUB:"\?\?\$__device_stub__kernelfunc@H@@YAXXZ.*"]], comdat, align 8
 // MSVC: @[[HDKERN:"\?kernel_decl@@YAXXZ.*"]] = external dso_local constant void ()*, al

[PATCH] D114058: [clangd] Add ObjC method support to prepareCallHierarchy

2021-11-23 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp:54
 
+void verifyIncomingMultiFile(std::string SourceExt, std::string HeaderExt,
+ Annotations &CalleeH, Annotations &Caller1H,

nridge wrote:
> nit: rather than passing `std::string` by value, let's use `llvm::StringRef`
> 
> (`const std::string&` would also be fine, but I think `llvm::StringRef` is 
> more conventional in this codebase)
i am not sure if these helpers makes tests easier to read (i believe they're 
actually making it harder).

please inline them back. if we want to have better infrastructure for testing 
this, we need to do it in its own patch (and I definitely agree that we need a 
better infra for testing here. but we need to think about something that can 
generalize rather than forcing a particular pattern).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114058

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


[PATCH] D114439: [Annotation] Allow parameter pack expansions in annotate attribute

2021-11-23 Thread Tyker via Phabricator via cfe-commits
Tyker added a comment.

This seems like a good change to me. but i don't think my approval is enough


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114439

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


[PATCH] D114088: [PowerPC] Add BCD add/sub/cmp builtins

2021-11-23 Thread Nemanja Ivanovic via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc933c2eb3346: [PowerPC] Add BCD add/sub/cmp builtins 
(authored by nemanjai).

Changed prior to commit:
  https://reviews.llvm.org/D114088?vs=387933&id=389238#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114088

Files:
  llvm/include/llvm/IR/IntrinsicsPowerPC.td
  llvm/lib/Target/PowerPC/P10InstrResources.td
  llvm/lib/Target/PowerPC/P9InstrResources.td
  llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp
  llvm/lib/Target/PowerPC/PPCInstrAltivec.td
  llvm/test/CodeGen/PowerPC/bcd-intrinsics.ll

Index: llvm/test/CodeGen/PowerPC/bcd-intrinsics.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/bcd-intrinsics.ll
@@ -0,0 +1,212 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-linux-gnu \
+; RUN:   -mcpu=pwr10 -ppc-asm-full-reg-names \
+; RUN:   -ppc-vsr-nums-as-vr < %s | FileCheck %s
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-linux-gnu \
+; RUN:   -mcpu=pwr9 -ppc-asm-full-reg-names \
+; RUN:   -ppc-vsr-nums-as-vr < %s | FileCheck %s --check-prefix=CHECK-P9
+
+define dso_local i64 @test_invalid(<16 x i8> %a) local_unnamed_addr #0 {
+; CHECK-LABEL: test_invalid:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:bcdsub. v2, v2, v2, 0
+; CHECK-NEXT:setbc r3, 4*cr6+un
+; CHECK-NEXT:extsw r3, r3
+; CHECK-NEXT:blr
+;
+; CHECK-P9-LABEL: test_invalid:
+; CHECK-P9:   # %bb.0: # %entry
+; CHECK-P9-NEXT:bcdsub. v2, v2, v2, 0
+; CHECK-P9-NEXT:mfocrf r3, 2
+; CHECK-P9-NEXT:rlwinm r3, r3, 28, 31, 31
+; CHECK-P9-NEXT:extsw r3, r3
+; CHECK-P9-NEXT:blr
+entry:
+  %0 = tail call i32 @llvm.ppc.bcdsub.p(i32 6, <16 x i8> %a, <16 x i8> %a) #2
+  %conv.i = sext i32 %0 to i64
+  ret i64 %conv.i
+}
+
+define dso_local <16 x i8> @test_add(<16 x i8> %a, <16 x i8> %b, i64 %ps) local_unnamed_addr #0 {
+; CHECK-LABEL: test_add:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:bcdadd. v2, v2, v3, 1
+; CHECK-NEXT:blr
+;
+; CHECK-P9-LABEL: test_add:
+; CHECK-P9:   # %bb.0: # %entry
+; CHECK-P9-NEXT:bcdadd. v2, v2, v3, 1
+; CHECK-P9-NEXT:blr
+entry:
+  %0 = tail call <16 x i8> @llvm.ppc.bcdadd(<16 x i8> %a, <16 x i8> %b, i32 1)
+  ret <16 x i8> %0
+}
+
+define dso_local i64 @test_add_ofl(<16 x i8> %a, <16 x i8> %b, i64 %ps) local_unnamed_addr #0 {
+; CHECK-LABEL: test_add_ofl:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:bcdadd. v2, v2, v3, 0
+; CHECK-NEXT:setbc r3, 4*cr6+un
+; CHECK-NEXT:extsw r3, r3
+; CHECK-NEXT:blr
+;
+; CHECK-P9-LABEL: test_add_ofl:
+; CHECK-P9:   # %bb.0: # %entry
+; CHECK-P9-NEXT:bcdadd. v2, v2, v3, 0
+; CHECK-P9-NEXT:mfocrf r3, 2
+; CHECK-P9-NEXT:rlwinm r3, r3, 28, 31, 31
+; CHECK-P9-NEXT:extsw r3, r3
+; CHECK-P9-NEXT:blr
+entry:
+  %0 = tail call i32 @llvm.ppc.bcdadd.p(i32 6, <16 x i8> %a, <16 x i8> %b) #2
+  %conv.i = sext i32 %0 to i64
+  ret i64 %conv.i
+}
+
+define dso_local <16 x i8> @test_sub(<16 x i8> %a, <16 x i8> %b, i64 %ps) local_unnamed_addr #0 {
+; CHECK-LABEL: test_sub:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:bcdsub. v2, v2, v3, 0
+; CHECK-NEXT:blr
+;
+; CHECK-P9-LABEL: test_sub:
+; CHECK-P9:   # %bb.0: # %entry
+; CHECK-P9-NEXT:bcdsub. v2, v2, v3, 0
+; CHECK-P9-NEXT:blr
+entry:
+  %0 = tail call <16 x i8> @llvm.ppc.bcdsub(<16 x i8> %a, <16 x i8> %b, i32 0)
+  ret <16 x i8> %0
+}
+
+define dso_local i64 @test_sub_ofl(<16 x i8> %a, <16 x i8> %b, i64 %ps) local_unnamed_addr #0 {
+; CHECK-LABEL: test_sub_ofl:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:bcdsub. v2, v2, v3, 0
+; CHECK-NEXT:setbc r3, 4*cr6+un
+; CHECK-NEXT:extsw r3, r3
+; CHECK-NEXT:blr
+;
+; CHECK-P9-LABEL: test_sub_ofl:
+; CHECK-P9:   # %bb.0: # %entry
+; CHECK-P9-NEXT:bcdsub. v2, v2, v3, 0
+; CHECK-P9-NEXT:mfocrf r3, 2
+; CHECK-P9-NEXT:rlwinm r3, r3, 28, 31, 31
+; CHECK-P9-NEXT:extsw r3, r3
+; CHECK-P9-NEXT:blr
+entry:
+  %0 = tail call i32 @llvm.ppc.bcdsub.p(i32 6, <16 x i8> %a, <16 x i8> %b) #2
+  %conv.i = sext i32 %0 to i64
+  ret i64 %conv.i
+}
+
+define dso_local i64 @test_cmplt(<16 x i8> %a, <16 x i8> %b) local_unnamed_addr #0 {
+; CHECK-LABEL: test_cmplt:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:bcdsub. v2, v2, v3, 0
+; CHECK-NEXT:setbc r3, 4*cr6+lt
+; CHECK-NEXT:extsw r3, r3
+; CHECK-NEXT:blr
+;
+; CHECK-P9-LABEL: test_cmplt:
+; CHECK-P9:   # %bb.0: # %entry
+; CHECK-P9-NEXT:bcdsub. v2, v2, v3, 0
+; CHECK-P9-NEXT:mfocrf r3, 2
+; CHECK-P9-NEXT:rlwinm r3, r3, 25, 31, 31
+; CHECK-P9-NEXT:extsw r3, r3
+; CHECK-P9-NEXT:blr
+entry:
+  %0 = tail call i32 @llvm.ppc.bcdsub.p(i32 2, <16 x i8> %a, <16 x i8> %b) #2
+  %conv.i = sext i32 %0 to i64
+  ret i64 %conv.i
+}
+
+define d

[PATCH] D114454: [NFC][AIX]Disable unstable CSA tests failing on AIX

2021-11-23 Thread Steven Wan via Phabricator via cfe-commits
stevewan created this revision.
stevewan requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

CSA uses bitwidth to infer the integer value type. In the ILP32 model, for 
example 32-bit AIX, any 32-bit integer type will be
considerred as `int`, which isn't always true. In these particular failed 
tests, CSA thinks the pointers should be `int`, while in fact they are long on 
AIX.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114454

Files:
  clang/unittests/StaticAnalyzer/SValTest.cpp


Index: clang/unittests/StaticAnalyzer/SValTest.cpp
===
--- clang/unittests/StaticAnalyzer/SValTest.cpp
+++ clang/unittests/StaticAnalyzer/SValTest.cpp
@@ -143,11 +143,19 @@
 // Actual tests
 
//===--===//
 
+#ifdef _AIX
+SVAL_TEST(DISABLED_GetConstType, R"(
+void foo() {
+  int x = 42;
+  int *y = nullptr;
+})") {
+#else
 SVAL_TEST(GetConstType, R"(
 void foo() {
   int x = 42;
   int *y = nullptr;
 })") {
+#endif
   SVal X = getByName("x");
   ASSERT_FALSE(X.getType(Context).isNull());
   EXPECT_EQ(Context.IntTy, X.getType(Context));
@@ -157,12 +165,21 @@
   EXPECT_EQ(Context.getUIntPtrType(), Y.getType(Context));
 }
 
+#ifdef _AIX
+SVAL_TEST(DISABLED_GetLocAsIntType, R"(
+void foo(int *x) {
+  long int a = (long int)x;
+  unsigned b = (long unsigned)&a;
+  int c = (long int)nullptr;
+})") {
+#else
 SVAL_TEST(GetLocAsIntType, R"(
 void foo(int *x) {
   long int a = (long int)x;
   unsigned b = (long unsigned)&a;
   int c = (long int)nullptr;
 })") {
+#endif
   SVal A = getByName("a");
   ASSERT_FALSE(A.getType(Context).isNull());
   // TODO: Turn it into signed long


Index: clang/unittests/StaticAnalyzer/SValTest.cpp
===
--- clang/unittests/StaticAnalyzer/SValTest.cpp
+++ clang/unittests/StaticAnalyzer/SValTest.cpp
@@ -143,11 +143,19 @@
 // Actual tests
 //===--===//
 
+#ifdef _AIX
+SVAL_TEST(DISABLED_GetConstType, R"(
+void foo() {
+  int x = 42;
+  int *y = nullptr;
+})") {
+#else
 SVAL_TEST(GetConstType, R"(
 void foo() {
   int x = 42;
   int *y = nullptr;
 })") {
+#endif
   SVal X = getByName("x");
   ASSERT_FALSE(X.getType(Context).isNull());
   EXPECT_EQ(Context.IntTy, X.getType(Context));
@@ -157,12 +165,21 @@
   EXPECT_EQ(Context.getUIntPtrType(), Y.getType(Context));
 }
 
+#ifdef _AIX
+SVAL_TEST(DISABLED_GetLocAsIntType, R"(
+void foo(int *x) {
+  long int a = (long int)x;
+  unsigned b = (long unsigned)&a;
+  int c = (long int)nullptr;
+})") {
+#else
 SVAL_TEST(GetLocAsIntType, R"(
 void foo(int *x) {
   long int a = (long int)x;
   unsigned b = (long unsigned)&a;
   int c = (long int)nullptr;
 })") {
+#endif
   SVal A = getByName("a");
   ASSERT_FALSE(A.getType(Context).isNull());
   // TODO: Turn it into signed long
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D108479: [Clang] Add __builtin_addressof_nocfi

2021-11-23 Thread Sami Tolvanen via Phabricator via cfe-commits
samitolvanen updated this revision to Diff 389242.
samitolvanen marked an inline comment as done.
samitolvanen added a comment.

Refactored to avoid evaluating the expression into an l-value.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D108479

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/AST/Expr.h
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/AST/Expr.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGExprConstant.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
  clang/test/CodeGen/builtin-function-start.cpp
  clang/test/SemaCXX/builtins.cpp

Index: clang/test/SemaCXX/builtins.cpp
===
--- clang/test/SemaCXX/builtins.cpp
+++ clang/test/SemaCXX/builtins.cpp
@@ -39,6 +39,13 @@
   S *ptmp = __builtin_addressof(S{}); // expected-error {{taking the address of a temporary}}
 }
 
+namespace function_start {
+void a(void) {}
+int n;
+void *p = __builtin_function_start(n);   // expected-error {{argument must be a function}}
+static_assert(__builtin_function_start(a) == a, ""); // expected-error {{static_assert expression is not an integral constant expression}}
+} // namespace function_start
+
 void no_ms_builtins() {
   __assume(1); // expected-error {{use of undeclared}}
   __noop(1); // expected-error {{use of undeclared}}
Index: clang/test/CodeGen/builtin-function-start.cpp
===
--- /dev/null
+++ clang/test/CodeGen/builtin-function-start.cpp
@@ -0,0 +1,51 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -fsanitize=cfi-icall -o - %s | FileCheck %s
+
+#if !__has_builtin(__builtin_function_start)
+#error "missing __builtin_function_start"
+#endif
+
+void a(void) {}
+void b(void) {}
+void c(void *p) {}
+
+// CHECK: @e = global i8* bitcast (void ()* no_cfi @_Z1av to i8*)
+const void *e = __builtin_function_start(a);
+// CHECK: @f = global [2 x i8*] [i8* bitcast (void ()* @_Z1bv to i8*), i8* bitcast (void ()* no_cfi @_Z1bv to i8*)]
+void *f[] = {(void *)b, __builtin_function_start(b)};
+
+class A {
+public:
+  void f();
+  virtual void g();
+  static void h();
+  int i() const;
+  int i(int n) const;
+};
+
+void A::f() {}
+void A::g() {}
+void A::h() {}
+
+// CHECK: define {{.*}}i32 @_ZNK1A1iEv(%class.A* {{.*}}%this)
+int A::i() const { return 0; }
+
+// CHECK: define {{.*}}i32 @_ZNK1A1iEi(%class.A* {{.*}}%this, i32 %n)
+int A::i(int n) const { return 0; }
+
+void d(void) {
+  // CHECK: store i8* bitcast (void ()* no_cfi @_Z1bv to i8*), i8** %g
+  void *g = __builtin_function_start(b);
+  // call void @_Z1cPv(i8* bitcast (void ()* no_cfi @_Z1av to i8*))
+  c(__builtin_function_start(a));
+
+  // CHECK: store i8* bitcast (void (%class.A*)* no_cfi @_ZN1A1fEv to i8*), i8** %Af
+  void *Af = __builtin_function_start(&A::f);
+  // CHECK: store i8* bitcast (void (%class.A*)* no_cfi @_ZN1A1gEv to i8*), i8** %Ag
+  void *Ag = __builtin_function_start(&A::g);
+  // CHECK: store i8* bitcast (void ()* no_cfi @_ZN1A1hEv to i8*), i8** %Ah
+  void *Ah = __builtin_function_start(&A::h);
+  // CHECK: store i8* bitcast (i32 (%class.A*)* no_cfi @_ZNK1A1iEv to i8*), i8** %Ai1
+  void *Ai1 = __builtin_function_start((int(A::*)() const) & A::i);
+  // CHECK: store i8* bitcast (i32 (%class.A*, i32)* no_cfi @_ZNK1A1iEi to i8*), i8** %Ai2
+  void *Ai2 = __builtin_function_start((int(A::*)(int) const) & A::i);
+}
Index: clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
@@ -66,7 +66,8 @@
   case Builtin::BI__builtin_expect:
   case Builtin::BI__builtin_expect_with_probability:
   case Builtin::BI__builtin_assume_aligned:
-  case Builtin::BI__builtin_addressof: {
+  case Builtin::BI__builtin_addressof:
+  case Builtin::BI__builtin_function_start: {
 // For __builtin_unpredictable, __builtin_expect,
 // __builtin_expect_with_probability and __builtin_assume_aligned,
 // just return the value of the subexpression.
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -195,6 +195,23 @@
   return false;
 }
 
+/// Check that the argument to __builtin_function_start is a function.
+static bool SemaBuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
+  if (checkArgCount(S, TheCall, 1))
+return true;
+
+  const FunctionDecl *FD =
+  dyn_cast_or_null(TheCall->getArgDecl(S.getASTContext()));
+  if (!FD) {
+S.Diag(Th

[PATCH] D108479: [Clang] Add __builtin_addressof_nocfi

2021-11-23 Thread Sami Tolvanen via Phabricator via cfe-commits
samitolvanen added a comment.

In D108479#3140688 , @rjmccall wrote:

> In D108479#3140638 , @samitolvanen 
> wrote:
>
>> Sure, I can take a look at how that would work. Basically, in 
>> `PointerExprEvaluator::VisitBuiltinCallExpr` we should not evaluate the 
>> l-value and just leave it at `Result.set(E)`?
>
> Yes, exactly.  Since the builtin already requires a constant operand in 
> non-dependent contexts, that should be enough.

This does indeed solve comparison issues and allows me to drop the changes to 
`APValue`, but it breaks initializing globals in C because Clang doesn't know 
the expression is a compile-time constant:

  $ cat test.c
  void a() {}
  const void *p = __builtin_function_start(a);
  $ clang -c test.c
  test.c:2:17: error: initializer element is not a compile-time constant
  const void *p = __builtin_function_start(a);
  ^~~
  1 error generated.

I worked around this for now by explicitly allowing `__builtin_function_start` 
in `CheckLValueConstantExpression`, but this seems terribly hacky. What would 
be the correct way to solve this issue?




Comment at: clang/lib/Sema/SemaChecking.cpp:208
+if (UnaryOp->getOpcode() == UnaryOperator::Opcode::UO_AddrOf)
+  E = UnaryOp->getSubExpr();
+

rjmccall wrote:
> It would be more general to allow any expression that we can 
> constant-evaluate to a specific function / member function reference.  That 
> allows callers to do stuff like `__builtin_function_start((int (A::*)() 
> const) &A::x)` to resolve overloaded function references.
> 
> You should delay this check if the operand is value-dependent.
> It would be more general to allow any expression that we can 
> constant-evaluate to a specific function / member function reference.  That 
> allows callers to do stuff like `__builtin_function_start((int (A::*)() 
> const) &A::x)` to resolve overloaded function references.

I looked into using `Expr::EvaluateAsConstantExpr` here and while it works, I'm 
not sure if allowing arbitrary expressions as the argument provides any value. 
We can allow resolving overloaded function references without 
constant-evaluating the expression (and I added tests for this). Did you have 
any other use cases in mind where this might be useful?



Comment at: clang/lib/Sema/SemaChecking.cpp:221
+  if (ResultType.isNull())
+return true;
+

rjmccall wrote:
> I think we decided that the result type should be `void*`.  Are there other 
> semantic checks from `CheckAddressOfOperand` that still meaningfully apply?
I thought `Sema::checkAddressOfFunctionIsAvailable` would be useful.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D108479

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


[PATCH] D110927: [analyzer] Access stored value of a constant array through a pointer to another type

2021-11-23 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov abandoned this revision.
ASDenysPetrov added a comment.

Temporary suspended this revision in favor of making a new checker 
//StrictAliasingChecker//, which would define an access to values through 
unpermited types as Unefined Behavior according to certain statements of the 
current Standard.


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

https://reviews.llvm.org/D110927

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


[PATCH] D108479: [Clang] Add __builtin_addressof_nocfi

2021-11-23 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

In D108479#3149228 , @samitolvanen 
wrote:

> I worked around this for now by explicitly allowing 
> `__builtin_function_start` in `CheckLValueConstantExpression`, but this seems 
> terribly hacky. What would be the correct way to solve this issue?

Try to generalize what we do for `__builtin___CFStringMakeConstantString`.




Comment at: clang/lib/Sema/SemaChecking.cpp:208
+if (UnaryOp->getOpcode() == UnaryOperator::Opcode::UO_AddrOf)
+  E = UnaryOp->getSubExpr();
+

samitolvanen wrote:
> rjmccall wrote:
> > It would be more general to allow any expression that we can 
> > constant-evaluate to a specific function / member function reference.  That 
> > allows callers to do stuff like `__builtin_function_start((int (A::*)() 
> > const) &A::x)` to resolve overloaded function references.
> > 
> > You should delay this check if the operand is value-dependent.
> > It would be more general to allow any expression that we can 
> > constant-evaluate to a specific function / member function reference.  That 
> > allows callers to do stuff like `__builtin_function_start((int (A::*)() 
> > const) &A::x)` to resolve overloaded function references.
> 
> I looked into using `Expr::EvaluateAsConstantExpr` here and while it works, 
> I'm not sure if allowing arbitrary expressions as the argument provides any 
> value. We can allow resolving overloaded function references without 
> constant-evaluating the expression (and I added tests for this). Did you have 
> any other use cases in mind where this might be useful?
I don't see what the advantage of limiting the constant expression would be if 
we can constant-evaluate it.  `switch` doesn't force you to make case values be 
integer literals and/or references to enumerators.  What are you trying to 
achieve with a restriction?

Not having arbitrary restrictions is particularly useful in C++, where 
templates and `constexpr` machinery can usefully do a lot of abstraction.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D108479

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


[PATCH] D108479: [Clang] Add __builtin_addressof_nocfi

2021-11-23 Thread Sami Tolvanen via Phabricator via cfe-commits
samitolvanen planned changes to this revision.
samitolvanen added a comment.

In D108479#3149297 , @rjmccall wrote:

> In D108479#3149228 , @samitolvanen 
> wrote:
>
>> I worked around this for now by explicitly allowing 
>> `__builtin_function_start` in `CheckLValueConstantExpression`, but this 
>> seems terribly hacky. What would be the correct way to solve this issue?
>
> Try to generalize what we do for `__builtin___CFStringMakeConstantString`.

Thanks, I'll take a look.




Comment at: clang/lib/Sema/SemaChecking.cpp:208
+if (UnaryOp->getOpcode() == UnaryOperator::Opcode::UO_AddrOf)
+  E = UnaryOp->getSubExpr();
+

rjmccall wrote:
> samitolvanen wrote:
> > rjmccall wrote:
> > > It would be more general to allow any expression that we can 
> > > constant-evaluate to a specific function / member function reference.  
> > > That allows callers to do stuff like `__builtin_function_start((int 
> > > (A::*)() const) &A::x)` to resolve overloaded function references.
> > > 
> > > You should delay this check if the operand is value-dependent.
> > > It would be more general to allow any expression that we can 
> > > constant-evaluate to a specific function / member function reference.  
> > > That allows callers to do stuff like `__builtin_function_start((int 
> > > (A::*)() const) &A::x)` to resolve overloaded function references.
> > 
> > I looked into using `Expr::EvaluateAsConstantExpr` here and while it works, 
> > I'm not sure if allowing arbitrary expressions as the argument provides any 
> > value. We can allow resolving overloaded function references without 
> > constant-evaluating the expression (and I added tests for this). Did you 
> > have any other use cases in mind where this might be useful?
> I don't see what the advantage of limiting the constant expression would be 
> if we can constant-evaluate it.  `switch` doesn't force you to make case 
> values be integer literals and/or references to enumerators.  What are you 
> trying to achieve with a restriction?
> 
> Not having arbitrary restrictions is particularly useful in C++, where 
> templates and `constexpr` machinery can usefully do a lot of abstraction.
> I don't see what the advantage of limiting the constant expression would be 
> if we can constant-evaluate it.  `switch` doesn't force you to make case 
> values be integer literals and/or references to enumerators.  What are you 
> trying to achieve with a restriction?

I'm trying to understand the benefit of allowing arbitrary expressions like 
`__builtin_function_start(100 + a)`, which `EvaluateAsConstantExpr` is happy to 
evaluate into a reference to `a`.

I can obviously understand why these should be allowed for `switch`, but here 
we have a function whose sole purpose is to return the address of a function 
and I'm wondering why someone would want pass anything more complicated to it.

> Not having arbitrary restrictions is particularly useful in C++, where 
> templates and `constexpr` machinery can usefully do a lot of abstraction.

Perhaps I'm just not that familiar with the C++ use cases here. Would you be 
able to provide me an example I could use as a test case?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D108479

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


[PATCH] D110663: [Driver] Support Debian multiarch style lib/clang/14.0.0/x86_64-linux-gnu runtime path and include/x86_64-linux-gnu/c++/v1 libc++ path

2021-11-23 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D110663#3148690 , @sylvestre.ledru 
wrote:

> I am not sure why you are pinging this review often?! Maybe chat with people 
> who gave you feedback before directly?!

https://llvm.org/docs/CodeReview.html "If it is not urgent, the common courtesy 
ping rate is one week." I did it less frequently than once per week.

Ping @phosek

> Myself I wasted so much time because of D107799 
>  that I am very reluctant to enable 
> LLVM_ENABLE_PER_TARGET_RUNTIME_DIR again.
> The mismatch of the triple / quadruple between the system triple and what 
> have been decided in llvm ( x86_64-linux-gnu vs x86_64-pc-linux-gnu)
>
>> Moreover, llvm-project has always had the attitude: "downstream projects are 
>> on their own".
>
> I am not sure it is a correct statement. llvm project is a bunch of people 
> with different focus. 
> But in general, we are trying to be nice with the ecosystem and people who 
> rely on this software.

Still correct. For courtesy I typically notify projects but many changes 
(especially IR and codegen changes) cannot really notify users simply because 
you cannot enumerate every user and
in some IR/codegen folks's minds this would unnecessarily slow down development.
For this case I have notified rust, which may be the most likely impacted user. 
I think the mostly likely impacted user is probably just Fuchsia.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110663

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


[PATCH] D110663: [Driver] Support Debian multiarch style lib/clang/14.0.0/x86_64-linux-gnu runtime path and include/x86_64-linux-gnu/c++/v1 libc++ path

2021-11-23 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

Were you able to actually reproduce the problem that lead to revert of D107799 
, or is this based on blind guesses?

In D110663#3149364 , @MaskRay wrote:

> In D110663#3148690 , 
> @sylvestre.ledru wrote:
>
>> I am not sure why you are pinging this review often?! Maybe chat with people 
>> who gave you feedback before directly?!
>
> https://llvm.org/docs/CodeReview.html "If it is not urgent, the common 
> courtesy ping rate is one week." I did it less frequently than once per week.
>
> Ping @phosek
>
>> Myself I wasted so much time because of D107799 
>>  that I am very reluctant to enable 
>> LLVM_ENABLE_PER_TARGET_RUNTIME_DIR again.
>> The mismatch of the triple / quadruple between the system triple and what 
>> have been decided in llvm ( x86_64-linux-gnu vs x86_64-pc-linux-gnu)
>>
>>> Moreover, llvm-project has always had the attitude: "downstream projects 
>>> are on their own".
>>
>> I am not sure it is a correct statement. llvm project is a bunch of people 
>> with different focus. 
>> But in general, we are trying to be nice with the ecosystem and people who 
>> rely on this software.
>
> Still correct. For courtesy I typically notify projects but many changes 
> (especially IR and codegen changes) cannot really notify users simply because 
> you cannot enumerate every user and
> in some IR/codegen folks's minds this would unnecessarily slow down 
> development.
> For this case I have notified rust, which may be the most likely impacted 
> user. I think the mostly likely impacted user was probably just Fuchsia, but 
> I have added a hack to exclude Fuchsia.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110663

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


[PATCH] D110663: [Driver] Support Debian multiarch style lib/clang/14.0.0/x86_64-linux-gnu runtime path and include/x86_64-linux-gnu/c++/v1 libc++ path

2021-11-23 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D110663#3149389 , @lebedev.ri 
wrote:

> Were you able to actually reproduce the problem that lead to revert of 
> D107799 , or is this based on blind guesses?

The patch will fix the "lib/clang/14.0.0/x86_64-unknown-linux-gnu/" issue on 
Debian/Ubuntu and their derivatives:
if Debian multiarch LLVM_DEFAULT_TARGET_TRIPLE=x86_64-linux-gnu is used, the 
`-unknown` should not be present.
I have noticed the issue on my Debian testing machine.

Whether this helps the revert of D107799  
(`-DLLVM_ENABLE_PER_TARGET_RUNTIME_DIR=on`): blind guess.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110663

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


[PATCH] D114317: [clang-tidy][WIP] Do not run perfect alias checks

2021-11-23 Thread Salman Javed via Phabricator via cfe-commits
salman-javed-nz added a comment.

What would you say are the key differences between this patch differ and 
previous attempts, e.g. https://reviews.llvm.org/D72566? How does this patch 
address the concerns raised in the previous reviews?


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

https://reviews.llvm.org/D114317

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


  1   2   >