[PATCH] D118196: [syntax][pseudo] Implement LR parsing table.

2022-02-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 410725.
hokein marked 3 inline comments as done.
hokein added a comment.

address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118196

Files:
  clang/include/clang/Tooling/Syntax/Pseudo/Grammar.h
  clang/include/clang/Tooling/Syntax/Pseudo/LRTable.h
  clang/lib/Tooling/Syntax/Pseudo/CMakeLists.txt
  clang/lib/Tooling/Syntax/Pseudo/Grammar.cpp
  clang/lib/Tooling/Syntax/Pseudo/GrammarBNF.cpp
  clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
  clang/lib/Tooling/Syntax/Pseudo/LRTableBuild.cpp
  clang/test/Syntax/check-cxx-bnf.test
  clang/test/Syntax/lr-build-basic.test
  clang/test/Syntax/lr-build-conflicts.test
  clang/tools/clang-pseudo/ClangPseudo.cpp
  clang/unittests/Tooling/Syntax/Pseudo/CMakeLists.txt
  clang/unittests/Tooling/Syntax/Pseudo/LRGraphTest.cpp
  clang/unittests/Tooling/Syntax/Pseudo/LRTableTest.cpp

Index: clang/unittests/Tooling/Syntax/Pseudo/LRTableTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/Syntax/Pseudo/LRTableTest.cpp
@@ -0,0 +1,56 @@
+//===--- LRTableTest.cpp - ---*- 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
+//
+//===--===//
+
+#include "clang/Tooling/Syntax/Pseudo/LRTable.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Tooling/Syntax/Pseudo/Grammar.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace clang {
+namespace syntax {
+namespace pseudo {
+namespace {
+
+using testing::IsEmpty;
+using testing::UnorderedElementsAre;
+using Action = LRTable::Action;
+
+TEST(LRTable, Builder) {
+  GrammarTable GTable;
+
+  //   eof   semi  ...
+  // +---++---+---
+  // |state0 || s0,r0 |...
+  // |state1 | acc|   |...
+  // |state2 ||  r1   |...
+  // +---++---+---
+  std::vector Entries = {
+  {/* State */ 0, tokenSymbol(tok::semi), Action::shift(0)},
+  {/* State */ 0, tokenSymbol(tok::semi), Action::reduce(0)},
+  {/* State */ 1, tokenSymbol(tok::eof), Action::accept(2)},
+  {/* State */ 2, tokenSymbol(tok::semi), Action::reduce(1)}};
+  GrammarTable GT;
+  LRTable T = LRTable::buildForTests(GT, Entries);
+  EXPECT_THAT(T.find(0, tokenSymbol(tok::eof)), IsEmpty());
+  EXPECT_THAT(T.find(0, tokenSymbol(tok::semi)),
+  UnorderedElementsAre(Action::shift(0), Action::reduce(0)));
+  EXPECT_THAT(T.find(1, tokenSymbol(tok::eof)),
+  UnorderedElementsAre(Action::accept(2)));
+  EXPECT_THAT(T.find(1, tokenSymbol(tok::semi)), IsEmpty());
+  EXPECT_THAT(T.find(2, tokenSymbol(tok::semi)),
+  UnorderedElementsAre(Action::reduce(1)));
+  // Verify the behaivor for other non-available-actions terminals.
+  EXPECT_THAT(T.find(2, tokenSymbol(tok::kw_int)), IsEmpty());
+}
+
+} // namespace
+} // namespace pseudo
+} // namespace syntax
+} // namespace clang
Index: clang/unittests/Tooling/Syntax/Pseudo/LRGraphTest.cpp
===
--- clang/unittests/Tooling/Syntax/Pseudo/LRGraphTest.cpp
+++ /dev/null
@@ -1,84 +0,0 @@
-//===--- LRGraphTest.cpp - LRGraph tests -*- 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
-//
-//===--===//
-
-#include "clang/Tooling/Syntax/Pseudo/LRGraph.h"
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include 
-
-namespace clang {
-namespace syntax {
-namespace pseudo {
-namespace {
-
-TEST(LRGraph, Build) {
-  struct TestCase {
-llvm::StringRef BNF;
-llvm::StringRef ExpectedStates;
-  };
-
-  TestCase Cases[] = {{
-  R"bnf(
-_ := expr
-expr := IDENTIFIER
-  )bnf",
-  R"(States:
-State 0
-_ :=  • expr
-expr :=  • IDENTIFIER
-State 1
-_ := expr • 
-State 2
-expr := IDENTIFIER • 
-0 ->[expr] 1
-0 ->[IDENTIFIER] 2
-)"},
-  {// A grammar with a S/R conflict in SLR table:
-   // (id-id)-id, or id-(id-id).
-   R"bnf(
-_ := expr
-expr := expr - expr  # S/R conflict at state 4 on '-' token
-expr := IDENTIFIER
-  )bnf",
-   R"(States:
-State 0
-_ :=  • expr
-expr :=  • expr - expr
-expr :=  • IDENTIFIER
-State 1
-_ := expr • 
-expr := expr • - expr
-State 2
-expr := IDENTIFIER • 
-State 3
-expr :=  • expr - expr
-expr := expr - • expr
-expr :=  • I

[PATCH] D120391: [Driver] Add -fno-sanitize-address-globals-dead-stripping

2022-02-23 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay created this revision.
MaskRay added reviewers: kstoimenov, vitalybuka.
Herald added a subscriber: dang.
MaskRay requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

It's customary for these options to have the -fno- form which is sometimes
handy to work around issues.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120391

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/Driver/fsanitize.c


Index: clang/test/Driver/fsanitize.c
===
--- clang/test/Driver/fsanitize.c
+++ clang/test/Driver/fsanitize.c
@@ -242,6 +242,7 @@
 
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=address 
-fsanitize-address-globals-dead-stripping %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-ASAN-GLOBALS
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=address %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-NO-ASAN-GLOBALS
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=address 
-fsanitize-address-globals-dead-stripping 
-fno-sanitize-address-globals-dead-stripping %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-NO-ASAN-GLOBALS
 // RUN: %clang_cl --target=x86_64-windows-msvc -fsanitize=address 
-fsanitize-address-globals-dead-stripping -### -- %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-ASAN-GLOBALS
 // RUN: %clang_cl --target=x86_64-windows-msvc -fsanitize=address -### -- %s 
2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-GLOBALS
 // RUN: %clang -target x86_64-scei-ps4  -fsanitize=address %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-ASAN-GLOBALS
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -848,10 +848,11 @@
 // As a workaround for a bug in gold 2.26 and earlier, dead stripping of
 // globals in ASan is disabled by default on ELF targets.
 // See https://sourceware.org/bugzilla/show_bug.cgi?id=19002
-AsanGlobalsDeadStripping =
+AsanGlobalsDeadStripping = Args.hasFlag(
+options::OPT_fsanitize_address_globals_dead_stripping,
+options::OPT_fno_sanitize_address_globals_dead_stripping,
 !TC.getTriple().isOSBinFormatELF() || TC.getTriple().isOSFuchsia() ||
-TC.getTriple().isPS4() ||
-Args.hasArg(options::OPT_fsanitize_address_globals_dead_stripping);
+TC.getTriple().isPS4());
 
 AsanUseOdrIndicator =
 Args.hasFlag(options::OPT_fsanitize_address_use_odr_indicator,
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1662,9 +1662,11 @@
   PosFlag, NegFlag,
   BothFlags<[], " poisoning array cookies when using custom operator new[] in 
AddressSanitizer">>,
   Group;
-def fsanitize_address_globals_dead_stripping : Flag<["-"], 
"fsanitize-address-globals-dead-stripping">,
-  Group, HelpText<"Enable linker dead stripping of globals in 
AddressSanitizer">,
-  MarshallingInfoFlag, 
"false">;
+defm sanitize_address_globals_dead_stripping : BoolOption<"f", 
"sanitize-address-globals-dead-stripping",
+  CodeGenOpts<"SanitizeAddressGlobalsDeadStripping">, DefaultFalse,
+  PosFlag,
+  NegFlag>,
+  Group;
 defm sanitize_address_use_odr_indicator : BoolOption<"f", 
"sanitize-address-use-odr-indicator",
   CodeGenOpts<"SanitizeAddressUseOdrIndicator">, DefaultFalse,
   PosFlagIndex: clang/test/Driver/fsanitize.c
===
--- clang/test/Driver/fsanitize.c
+++ clang/test/Driver/fsanitize.c
@@ -242,6 +242,7 @@
 
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=address -fsanitize-address-globals-dead-stripping %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-GLOBALS
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ASAN-GLOBALS
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=address -fsanitize-address-globals-dead-stripping -fno-sanitize-address-globals-dead-stripping %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ASAN-GLOBALS
 // RUN: %clang_cl --target=x86_64-windows-msvc -fsanitize=address -fsanitize-address-globals-dead-stripping -### -- %s 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-GLOBALS
 // RUN: %clang_cl --target=x86_64-windows-msvc -fsanitize=address -### -- %s 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-GLOBALS
 // RUN: %clang -target x86_64-scei-ps4  -fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-GLOBALS
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -848,10 +848,11 @@
 // As a workaround for a bug in gold 2.26 and earlier, dead stripping of
 // glo

[PATCH] D120359: [clang-format][NFC] Remove redundant semi

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

I don't really understand this change. You say in the description that you 
remove the semicolon, but you actually add it.
Also, it's a common pattern not to add a semicolon and make all macro calls 
look like a normal statement (with a semi at the call place).
I'm not opposed but I don't see a reason for changing this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120359

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


[clang] a2fab82 - [pseudo] Implement LRTable.

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

Author: Haojian Wu
Date: 2022-02-23T09:21:34+01:00
New Revision: a2fab82f33bb8cc38cd1dfe7856dae706ce4297a

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

LOG: [pseudo] Implement LRTable.

This patch introduces a dense implementation of the LR parsing table, which is
used by LR parsers.

We build a SLR(1) parsing table from the LR(0) graph.

Statistics of the LR parsing table on the C++ spec grammar:
  - number of states: 1449
  - number of actions: 83069
  - size of the table (bytes): 334928

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

Added: 
clang/include/clang/Tooling/Syntax/Pseudo/LRTable.h
clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
clang/lib/Tooling/Syntax/Pseudo/LRTableBuild.cpp
clang/test/Syntax/lr-build-basic.test
clang/test/Syntax/lr-build-conflicts.test
clang/unittests/Tooling/Syntax/Pseudo/LRTableTest.cpp

Modified: 
clang/include/clang/Tooling/Syntax/Pseudo/Grammar.h
clang/lib/Tooling/Syntax/Pseudo/CMakeLists.txt
clang/lib/Tooling/Syntax/Pseudo/Grammar.cpp
clang/lib/Tooling/Syntax/Pseudo/GrammarBNF.cpp
clang/test/Syntax/check-cxx-bnf.test
clang/tools/clang-pseudo/ClangPseudo.cpp
clang/unittests/Tooling/Syntax/Pseudo/CMakeLists.txt

Removed: 
clang/unittests/Tooling/Syntax/Pseudo/LRGraphTest.cpp



diff  --git a/clang/include/clang/Tooling/Syntax/Pseudo/Grammar.h 
b/clang/include/clang/Tooling/Syntax/Pseudo/Grammar.h
index a7ecfea902b6d..086809ef41423 100644
--- a/clang/include/clang/Tooling/Syntax/Pseudo/Grammar.h
+++ b/clang/include/clang/Tooling/Syntax/Pseudo/Grammar.h
@@ -154,6 +154,8 @@ std::vector> followSets(const 
Grammar &);
 // It can be constructed dynamically (from compiling BNF file) or statically
 // (a compiled data-source).
 struct GrammarTable {
+  GrammarTable();
+
   struct Nonterminal {
 std::string Name;
 // Corresponding rules that construct the non-terminal, it is a [start, 
end)
@@ -169,7 +171,7 @@ struct GrammarTable {
   std::vector Rules;
   // A table of terminals (aka tokens). It corresponds to the clang::Token.
   // clang::tok::TokenKind is the index of the table.
-  std::vector Terminals;
+  llvm::ArrayRef Terminals;
   // A table of nonterminals, sorted by name.
   // SymbolID is the index of the table.
   std::vector Nonterminals;

diff  --git a/clang/include/clang/Tooling/Syntax/Pseudo/LRTable.h 
b/clang/include/clang/Tooling/Syntax/Pseudo/LRTable.h
new file mode 100644
index 0..025f7f141633a
--- /dev/null
+++ b/clang/include/clang/Tooling/Syntax/Pseudo/LRTable.h
@@ -0,0 +1,182 @@
+//===--- LRTable.h - Define LR Parsing Table -*- 
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
+//
+//===--===//
+//
+//  The LRTable (referred as LR parsing table in the LR literature) is the core
+//  component in LR parsers, it drives the LR parsers by specifying an action 
to
+//  take given the current state on the top of the stack and the current
+//  lookahead token.
+//
+//  The LRTable can be described as a matrix where the rows represent
+//  the states of the LR graph, the columns represent the symbols of the
+//  grammar, and each entry of the matrix (called action) represents a
+//  state transition in the graph.
+//
+//  Typically, based on the category of the grammar symbol, the LRTable is
+//  broken into two logically separate tables:
+//- ACTION table with terminals as columns -- e.g ACTION[S, a] specifies
+//  next action (shift/reduce/accept/error) on state S under a lookahead
+//  terminal a
+//- GOTO table with nonterminals as columns -- e.g. GOTO[S, X] specify
+//  the state which we transist to from the state S with the nonterminal X
+//
+//  LRTable is *performance-critial* as it is consulted frequently during a
+//  parse. In general, LRTable is very sparse (most of the entries are empty).
+//  For example, for the C++ language, the SLR table has ~1500 states and 650
+//  symbols which results in a matrix having 975K entries, ~90% of entries are
+//  empty.
+//
+//  This file implements a speed-and-space-efficient LRTable.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLING_SYNTAX_PSEUDO_LRTABLE_H
+#define LLVM_CLANG_TOOLING_SYNTAX_PSEUDO_LRTABLE_H
+
+#include "clang/Tooling/Syntax/Pseudo/Grammar.h"
+#include "llvm/ADT/ArrayRef.h"
+#include 
+#include 
+
+namespace clang {
+namespace syntax {
+namespace pseudo {
+
+// Represents the LR parsing table, which can efficiently the question "what is
+// the next ste

[PATCH] D118196: [syntax][pseudo] Implement LR parsing table.

2022-02-23 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa2fab82f33bb: [pseudo] Implement LRTable. (authored by 
hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118196

Files:
  clang/include/clang/Tooling/Syntax/Pseudo/Grammar.h
  clang/include/clang/Tooling/Syntax/Pseudo/LRTable.h
  clang/lib/Tooling/Syntax/Pseudo/CMakeLists.txt
  clang/lib/Tooling/Syntax/Pseudo/Grammar.cpp
  clang/lib/Tooling/Syntax/Pseudo/GrammarBNF.cpp
  clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
  clang/lib/Tooling/Syntax/Pseudo/LRTableBuild.cpp
  clang/test/Syntax/check-cxx-bnf.test
  clang/test/Syntax/lr-build-basic.test
  clang/test/Syntax/lr-build-conflicts.test
  clang/tools/clang-pseudo/ClangPseudo.cpp
  clang/unittests/Tooling/Syntax/Pseudo/CMakeLists.txt
  clang/unittests/Tooling/Syntax/Pseudo/LRGraphTest.cpp
  clang/unittests/Tooling/Syntax/Pseudo/LRTableTest.cpp

Index: clang/unittests/Tooling/Syntax/Pseudo/LRTableTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/Syntax/Pseudo/LRTableTest.cpp
@@ -0,0 +1,56 @@
+//===--- LRTableTest.cpp - ---*- 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
+//
+//===--===//
+
+#include "clang/Tooling/Syntax/Pseudo/LRTable.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Tooling/Syntax/Pseudo/Grammar.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace clang {
+namespace syntax {
+namespace pseudo {
+namespace {
+
+using testing::IsEmpty;
+using testing::UnorderedElementsAre;
+using Action = LRTable::Action;
+
+TEST(LRTable, Builder) {
+  GrammarTable GTable;
+
+  //   eof   semi  ...
+  // +---++---+---
+  // |state0 || s0,r0 |...
+  // |state1 | acc|   |...
+  // |state2 ||  r1   |...
+  // +---++---+---
+  std::vector Entries = {
+  {/* State */ 0, tokenSymbol(tok::semi), Action::shift(0)},
+  {/* State */ 0, tokenSymbol(tok::semi), Action::reduce(0)},
+  {/* State */ 1, tokenSymbol(tok::eof), Action::accept(2)},
+  {/* State */ 2, tokenSymbol(tok::semi), Action::reduce(1)}};
+  GrammarTable GT;
+  LRTable T = LRTable::buildForTests(GT, Entries);
+  EXPECT_THAT(T.find(0, tokenSymbol(tok::eof)), IsEmpty());
+  EXPECT_THAT(T.find(0, tokenSymbol(tok::semi)),
+  UnorderedElementsAre(Action::shift(0), Action::reduce(0)));
+  EXPECT_THAT(T.find(1, tokenSymbol(tok::eof)),
+  UnorderedElementsAre(Action::accept(2)));
+  EXPECT_THAT(T.find(1, tokenSymbol(tok::semi)), IsEmpty());
+  EXPECT_THAT(T.find(2, tokenSymbol(tok::semi)),
+  UnorderedElementsAre(Action::reduce(1)));
+  // Verify the behaivor for other non-available-actions terminals.
+  EXPECT_THAT(T.find(2, tokenSymbol(tok::kw_int)), IsEmpty());
+}
+
+} // namespace
+} // namespace pseudo
+} // namespace syntax
+} // namespace clang
Index: clang/unittests/Tooling/Syntax/Pseudo/LRGraphTest.cpp
===
--- clang/unittests/Tooling/Syntax/Pseudo/LRGraphTest.cpp
+++ /dev/null
@@ -1,84 +0,0 @@
-//===--- LRGraphTest.cpp - LRGraph tests -*- 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
-//
-//===--===//
-
-#include "clang/Tooling/Syntax/Pseudo/LRGraph.h"
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include 
-
-namespace clang {
-namespace syntax {
-namespace pseudo {
-namespace {
-
-TEST(LRGraph, Build) {
-  struct TestCase {
-llvm::StringRef BNF;
-llvm::StringRef ExpectedStates;
-  };
-
-  TestCase Cases[] = {{
-  R"bnf(
-_ := expr
-expr := IDENTIFIER
-  )bnf",
-  R"(States:
-State 0
-_ :=  • expr
-expr :=  • IDENTIFIER
-State 1
-_ := expr • 
-State 2
-expr := IDENTIFIER • 
-0 ->[expr] 1
-0 ->[IDENTIFIER] 2
-)"},
-  {// A grammar with a S/R conflict in SLR table:
-   // (id-id)-id, or id-(id-id).
-   R"bnf(
-_ := expr
-expr := expr - expr  # S/R conflict at state 4 on '-' token
-expr := IDENTIFIER
-  )bnf",
-   R"(States:
-State 0
-_ :=  • expr
-expr :=  • expr - expr
-expr :=  • IDENTIFIER
-State 1
-_ := expr • 
-expr := expr • - expr
-State 2
-expr := IDENTIFIER • 
-S

[clang] 7ea103d - [clang][dataflow] Add support for global storage values

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

Author: Stanislav Gatev
Date: 2022-02-23T08:27:58Z
New Revision: 7ea103de140b59a64fc884fa90afd2213619384d

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

LOG: [clang][dataflow] Add support for global storage values

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

Reviewed-by: ymandel, xazax.hun

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

Added: 


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

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index af613c95bb8dc..bab20418a016a 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -49,6 +49,11 @@ enum class SkipPast {
 };
 
 /// Holds the state of the program (store and heap) at a given program point.
+///
+/// WARNING: Symbolic values that are created by the environment for static
+/// local and global variables are not currently invalidated on function calls.
+/// This is unsound and should be taken into account when designing dataflow
+/// analyses.
 class Environment {
 public:
   /// Supplements `Environment` with non-standard comparison and join

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index eca58b313761b..f20c747c56c2d 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -22,6 +22,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/Support/ErrorHandling.h"
+#include 
 #include 
 #include 
 
@@ -56,10 +57,55 @@ static bool equivalentValues(QualType Type, Value *Val1, 
Value *Val2,
   return Model.compareEquivalent(Type, *Val1, *Val2);
 }
 
+/// Initializes a global storage value.
+static void initGlobalVar(const VarDecl &D, Environment &Env) {
+  if (!D.hasGlobalStorage() ||
+  Env.getStorageLocation(D, SkipPast::None) != nullptr)
+return;
+
+  auto &Loc = Env.createStorageLocation(D);
+  Env.setStorageLocation(D, Loc);
+  if (auto *Val = Env.createValue(D.getType()))
+Env.setValue(Loc, *Val);
+}
+
+/// Initializes a global storage value.
+static void initGlobalVar(const Decl &D, Environment &Env) {
+  if (auto *V = dyn_cast(&D))
+initGlobalVar(*V, Env);
+}
+
+/// Initializes global storage values that are declared or referenced from
+/// sub-statements of `S`.
+// FIXME: Add support for resetting globals after function calls to enable
+// the implementation of sound analyses.
+static void initGlobalVars(const Stmt &S, Environment &Env) {
+  for (auto *Child : S.children()) {
+if (Child != nullptr)
+  initGlobalVars(*Child, Env);
+  }
+
+  if (auto *DS = dyn_cast(&S)) {
+if (DS->isSingleDecl()) {
+  const auto &D = *cast(DS->getSingleDecl());
+  initGlobalVar(D, Env);
+} else {
+  for (auto *D : DS->getDeclGroup())
+initGlobalVar(*D, Env);
+}
+  } else if (auto *E = dyn_cast(&S)) {
+initGlobalVar(*E->getDecl(), Env);
+  } else if (auto *E = dyn_cast(&S)) {
+initGlobalVar(*E->getMemberDecl(), Env);
+  }
+}
+
 Environment::Environment(DataflowAnalysisContext &DACtx,
  const DeclContext &DeclCtx)
 : Environment(DACtx) {
   if (const auto *FuncDecl = dyn_cast(&DeclCtx)) {
+assert(FuncDecl->getBody() != nullptr);
+initGlobalVars(*FuncDecl->getBody(), *this);
 for (const auto *ParamDecl : FuncDecl->parameters()) {
   assert(ParamDecl != nullptr);
   auto &ParamLoc = createStorageLocation(*ParamDecl);

diff  --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index cd9b8b0e454e4..4b5d23593a4bd 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -136,6 +136,11 @@ class TransferVisitor : public 
ConstStmtVisitor {
 // Group decls are converted into single decls in the CFG so the cast below
 // is safe.
 const auto &D = *cast(S->getSingleDecl());
+
+// Static local vars are already initialized in `Environment`.
+if (D.hasGlobalStorage())
+  return;
+
 auto &Loc = Env.createStorageLocation(D);
 Env.setStorageLocation(D, Loc);
 
@@ -291,6 +296,24 @@ class TransferVisitor : public 
ConstStmtVisitor {
 if (Member->isFunctionOrFunctionTemplate())
   return;
 
+if

[PATCH] D120149: [clang][dataflow] Add support for global storage values

2022-02-23 Thread Stanislav Gatev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7ea103de140b: [clang][dataflow] Add support for global 
storage values (authored by sgatev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120149

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -2153,4 +2153,171 @@
   });
 }
 
+TEST_F(TransferTest, StaticIntSingleVarDecl) {
+  std::string Code = R"(
+void target() {
+  static int Foo;
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+const StorageLocation *FooLoc =
+Env.getStorageLocation(*FooDecl, SkipPast::None);
+ASSERT_TRUE(isa_and_nonnull(FooLoc));
+
+const Value *FooVal = Env.getValue(*FooLoc);
+EXPECT_TRUE(isa_and_nonnull(FooVal));
+  });
+}
+
+TEST_F(TransferTest, StaticIntGroupVarDecl) {
+  std::string Code = R"(
+void target() {
+  static int Foo, Bar;
+  (void)0;
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+ASSERT_THAT(FooDecl, NotNull());
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const StorageLocation *FooLoc =
+Env.getStorageLocation(*FooDecl, SkipPast::None);
+ASSERT_TRUE(isa_and_nonnull(FooLoc));
+
+const StorageLocation *BarLoc =
+Env.getStorageLocation(*BarDecl, SkipPast::None);
+ASSERT_TRUE(isa_and_nonnull(BarLoc));
+
+const Value *FooVal = Env.getValue(*FooLoc);
+EXPECT_TRUE(isa_and_nonnull(FooVal));
+
+const Value *BarVal = Env.getValue(*BarLoc);
+EXPECT_TRUE(isa_and_nonnull(BarVal));
+
+EXPECT_NE(FooVal, BarVal);
+  });
+}
+
+TEST_F(TransferTest, GlobalIntVarDecl) {
+  std::string Code = R"(
+static int Foo;
+
+void target() {
+  int Bar = Foo;
+  int Baz = Foo;
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
+ASSERT_THAT(BazDecl, NotNull());
+
+const Value *BarVal =
+cast(Env.getValue(*BarDecl, SkipPast::None));
+const Value *BazVal =
+cast(Env.getValue(*BazDecl, SkipPast::None));
+EXPECT_EQ(BarVal, BazVal);
+  });
+}
+
+TEST_F(TransferTest, StaticMemberIntVarDecl) {
+  std::string Code = R"(
+struct A {
+  static int Foo;
+};
+
+void target(A a) {
+  int Bar = a.Foo;
+  int Baz = a.Foo;
+  // [[p]]
+}
+  )";
+  runDataflow(Code,
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
+ASSERT_THAT(BazDecl, NotNull());
+
+const Value *BarVal =
+cast(Env.getValue(*BarDecl, SkipPa

[clang] f85a6a8 - [NFC] Add unittest for Decl::isInExportDeclContext

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

Author: Chuanqi Xu
Date: 2022-02-23T16:29:42+08:00
New Revision: f85a6a812718cfdaeb1d0dc971ce3875aa82fafe

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

LOG: [NFC] Add unittest for Decl::isInExportDeclContext

Added: 


Modified: 
clang/unittests/AST/DeclTest.cpp

Removed: 




diff  --git a/clang/unittests/AST/DeclTest.cpp 
b/clang/unittests/AST/DeclTest.cpp
index 588ef859a181e..a84ebbd9835db 100644
--- a/clang/unittests/AST/DeclTest.cpp
+++ b/clang/unittests/AST/DeclTest.cpp
@@ -157,3 +157,17 @@ TEST(Decl, EnumDeclRange) {
   EXPECT_EQ(SM.getFileOffset(BarRange.getBegin()), Code.range().Begin);
   EXPECT_EQ(SM.getFileOffset(BarRange.getEnd()), Code.range().End);
 }
+
+TEST(Decl, IsInExportDeclContext) {
+  llvm::Annotations Code(R"(
+export module m;
+export template 
+void f() {})");
+  auto AST =
+  tooling::buildASTFromCodeWithArgs(Code.code(), /*Args=*/{"-std=c++20"});
+  ASTContext &Ctx = AST->getASTContext();
+
+  const auto *f =
+  selectFirst("f", match(functionDecl().bind("f"), Ctx));
+  EXPECT_TRUE(f->isInExportDeclContext());
+}



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


[clang] c34d898 - [ASTMatchers] Expand isInline matcher to VarDecl

2022-02-23 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-02-23T08:34:00Z
New Revision: c34d89818341b3c7c96bc8f59e3f98063d4ae9fd

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

LOG: [ASTMatchers] Expand isInline matcher to VarDecl

Add support to the `isInline` matcher for C++17's inline variables.

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/docs/LibASTMatchersReference.html
clang/docs/ReleaseNotes.rst
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/unittests/ASTMatchers/ASTMatchersInternalTest.cpp

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index a3f57996a6fb2..d552f4ccd7668 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -4322,7 +4322,7 @@ Narrowing Matchers
 
 
 MatcherFunctionDecl>isInline
-Matches function and 
namespace declarations that are marked with
+Matches functions, 
variables and namespace declarations that are marked with
 the inline keyword.
 
 Given
@@ -4331,8 +4331,10 @@ Narrowing Matchers
   namespace n {
   inline namespace m {}
   }
+  inline int Foo = 5;
 functionDecl(isInline()) will match ::f().
 namespaceDecl(isInline()) will match n::m.
+varDecl(isInline()) will match Foo;
 
 
 
@@ -4697,7 +4699,7 @@ Narrowing Matchers
 
 
 MatcherNamespaceDecl>isInline
-Matches function and 
namespace declarations that are marked with
+Matches functions, 
variables and namespace declarations that are marked with
 the inline keyword.
 
 Given
@@ -4706,8 +4708,10 @@ Narrowing Matchers
   namespace n {
   inline namespace m {}
   }
+  inline int Foo = 5;
 functionDecl(isInline()) will match ::f().
 namespaceDecl(isInline()) will match n::m.
+varDecl(isInline()) will match Foo;
 
 
 
@@ -5728,6 +5732,23 @@ Narrowing Matchers
 
 
 
+MatcherVarDecl>isInline
+Matches functions, 
variables and namespace declarations that are marked with
+the inline keyword.
+
+Given
+  inline void f();
+  void g();
+  namespace n {
+  inline namespace m {}
+  }
+  inline int Foo = 5;
+functionDecl(isInline()) will match ::f().
+namespaceDecl(isInline()) will match n::m.
+varDecl(isInline()) will match Foo;
+
+
+
 MatcherVarDecl>isStaticLocal
 Matches a static 
variable with local scope.
 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 68a867409c160..4131c022f5944 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -186,6 +186,8 @@ Build System Changes
 AST Matchers
 
 
+- Expanded ``isInline`` narrowing matcher to support c++17 inline variables.
+
 clang-format
 
 

diff  --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index 86bd44091b593..6664a5bcfe7fb 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -7673,7 +7673,7 @@ AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, 
internal::Matcher,
   return InnerMatcher.matches(*ES.getExpr(), Finder, Builder);
 }
 
-/// Matches function and namespace declarations that are marked with
+/// Matches functions, variables and namespace declarations that are marked 
with
 /// the inline keyword.
 ///
 /// Given
@@ -7683,18 +7683,22 @@ AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, 
internal::Matcher,
 ///   namespace n {
 ///   inline namespace m {}
 ///   }
+///   inline int Foo = 5;
 /// \endcode
 /// functionDecl(isInline()) will match ::f().
 /// namespaceDecl(isInline()) will match n::m.
-AST_POLYMORPHIC_MATCHER(isInline,
-AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
-FunctionDecl)) {
+/// varDecl(isInline()) will match Foo;
+AST_POLYMORPHIC_MATCHER(isInline, 
AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
+  FunctionDecl,
+  VarDecl)) {
   // This is required because the spelling of the function used to determine
   // whether inline is specified or not 
diff ers between the polymorphic types.
   if (const auto *FD = dyn_cast(&Node))
 return FD->isInlineSpecified();
-  else if (const auto *NSD = dyn_cast(&Node))
+  if (const auto *NSD = dyn_cast(&Node))
 return NSD->isInline();
+  if (const auto *VD = dyn_cast(&Node))
+return VD->isInline();
   llvm_unreachable("Not a valid polymorphic type");
 }
 

dif

[PATCH] D118900: [ASTMatchers] Expand isInline matcher to VarDecl

2022-02-23 Thread Nathan James 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 rGc34d89818341: [ASTMatchers] Expand isInline matcher to 
VarDecl (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118900

Files:
  clang/docs/LibASTMatchersReference.html
  clang/docs/ReleaseNotes.rst
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/unittests/ASTMatchers/ASTMatchersInternalTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersInternalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersInternalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersInternalTest.cpp
@@ -197,6 +197,8 @@
   functionDecl(isInline(), hasName("f";
   EXPECT_TRUE(matches("namespace n { inline namespace m {} }",
   namespaceDecl(isInline(), hasName("m";
+  EXPECT_TRUE(matches("inline int Foo = 5;",
+  varDecl(isInline(), hasName("Foo")), {Lang_CXX17}));
 }
 
 // FIXME: Figure out how to specify paths so the following tests pass on
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -7673,7 +7673,7 @@
   return InnerMatcher.matches(*ES.getExpr(), Finder, Builder);
 }
 
-/// Matches function and namespace declarations that are marked with
+/// Matches functions, variables and namespace declarations that are marked with
 /// the inline keyword.
 ///
 /// Given
@@ -7683,18 +7683,22 @@
 ///   namespace n {
 ///   inline namespace m {}
 ///   }
+///   inline int Foo = 5;
 /// \endcode
 /// functionDecl(isInline()) will match ::f().
 /// namespaceDecl(isInline()) will match n::m.
-AST_POLYMORPHIC_MATCHER(isInline,
-AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
-FunctionDecl)) {
+/// varDecl(isInline()) will match Foo;
+AST_POLYMORPHIC_MATCHER(isInline, AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
+  FunctionDecl,
+  VarDecl)) {
   // This is required because the spelling of the function used to determine
   // whether inline is specified or not differs between the polymorphic types.
   if (const auto *FD = dyn_cast(&Node))
 return FD->isInlineSpecified();
-  else if (const auto *NSD = dyn_cast(&Node))
+  if (const auto *NSD = dyn_cast(&Node))
 return NSD->isInline();
+  if (const auto *VD = dyn_cast(&Node))
+return VD->isInline();
   llvm_unreachable("Not a valid polymorphic type");
 }
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -186,6 +186,8 @@
 AST Matchers
 
 
+- Expanded ``isInline`` narrowing matcher to support c++17 inline variables.
+
 clang-format
 
 
Index: clang/docs/LibASTMatchersReference.html
===
--- clang/docs/LibASTMatchersReference.html
+++ clang/docs/LibASTMatchersReference.html
@@ -4322,7 +4322,7 @@
 
 
 MatcherFunctionDecl>isInline
-Matches function and namespace declarations that are marked with
+Matches functions, variables and namespace declarations that are marked with
 the inline keyword.
 
 Given
@@ -4331,8 +4331,10 @@
   namespace n {
   inline namespace m {}
   }
+  inline int Foo = 5;
 functionDecl(isInline()) will match ::f().
 namespaceDecl(isInline()) will match n::m.
+varDecl(isInline()) will match Foo;
 
 
 
@@ -4697,7 +4699,7 @@
 
 
 MatcherNamespaceDecl>isInline
-Matches function and namespace declarations that are marked with
+Matches functions, variables and namespace declarations that are marked with
 the inline keyword.
 
 Given
@@ -4706,8 +4708,10 @@
   namespace n {
   inline namespace m {}
   }
+  inline int Foo = 5;
 functionDecl(isInline()) will match ::f().
 namespaceDecl(isInline()) will match n::m.
+varDecl(isInline()) will match Foo;
 
 
 
@@ -5728,6 +5732,23 @@
 
 
 
+MatcherVarDecl>isInline
+Matches functions, variables and namespace declarations that are marked with
+the inline keyword.
+
+Given
+  inline void f();
+  void g();
+  namespace n {
+  inline namespace m {}
+  }
+  inline int Foo = 5;
+functionDecl(isInline()) will match ::f().
+namespaceDecl(isInline()) will match n::m.
+varDecl(isInline()) will match Foo;
+
+
+
 Matcher

[clang-tools-extra] 79353f9 - [clang-tidy][NFC] Remove Tristate from CachedGlobList

2022-02-23 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-02-23T08:35:31Z
New Revision: 79353f940cf441e69f32af0a78a48baee89e8517

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

LOG: [clang-tidy][NFC] Remove Tristate from CachedGlobList

The tristate is a little redundant as we can determine if the item was already 
in the cache based on the return from try_emplace.

Reviewed By: salman-javed-nz

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/GlobList.cpp
clang-tools-extra/clang-tidy/GlobList.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/GlobList.cpp 
b/clang-tools-extra/clang-tidy/GlobList.cpp
index fe41feef38abf..a55cac412cf63 100644
--- a/clang-tools-extra/clang-tidy/GlobList.cpp
+++ b/clang-tools-extra/clang-tidy/GlobList.cpp
@@ -65,16 +65,12 @@ bool GlobList::contains(StringRef S) const {
 }
 
 bool CachedGlobList::contains(StringRef S) const {
-  switch (auto &Result = Cache[S]) {
-  case Yes:
-return true;
-  case No:
-return false;
-  case None:
-Result = GlobList::contains(S) ? Yes : No;
-return Result == Yes;
-  }
-  llvm_unreachable("invalid enum");
+  auto Entry = Cache.try_emplace(S);
+  bool &Value = Entry.first->getValue();
+  // If the entry was just inserted, determine its required value.
+  if (Entry.second)
+Value = GlobList::contains(S);
+  return Value;
 }
 
 } // namespace tidy

diff  --git a/clang-tools-extra/clang-tidy/GlobList.h 
b/clang-tools-extra/clang-tidy/GlobList.h
index de7020ef3f165..3eec92edaa695 100644
--- a/clang-tools-extra/clang-tidy/GlobList.h
+++ b/clang-tools-extra/clang-tidy/GlobList.h
@@ -59,8 +59,7 @@ class CachedGlobList final : public GlobList {
   bool contains(StringRef S) const override;
 
 private:
-  enum Tristate { None, Yes, No };
-  mutable llvm::StringMap Cache;
+  mutable llvm::StringMap Cache;
 };
 
 } // namespace tidy



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


[PATCH] D120196: [clang-tidy][NFC] Remove Tristate from CachedGlobList

2022-02-23 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG79353f940cf4: [clang-tidy][NFC] Remove Tristate from 
CachedGlobList (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120196

Files:
  clang-tools-extra/clang-tidy/GlobList.cpp
  clang-tools-extra/clang-tidy/GlobList.h


Index: clang-tools-extra/clang-tidy/GlobList.h
===
--- clang-tools-extra/clang-tidy/GlobList.h
+++ clang-tools-extra/clang-tidy/GlobList.h
@@ -59,8 +59,7 @@
   bool contains(StringRef S) const override;
 
 private:
-  enum Tristate { None, Yes, No };
-  mutable llvm::StringMap Cache;
+  mutable llvm::StringMap Cache;
 };
 
 } // namespace tidy
Index: clang-tools-extra/clang-tidy/GlobList.cpp
===
--- clang-tools-extra/clang-tidy/GlobList.cpp
+++ clang-tools-extra/clang-tidy/GlobList.cpp
@@ -65,16 +65,12 @@
 }
 
 bool CachedGlobList::contains(StringRef S) const {
-  switch (auto &Result = Cache[S]) {
-  case Yes:
-return true;
-  case No:
-return false;
-  case None:
-Result = GlobList::contains(S) ? Yes : No;
-return Result == Yes;
-  }
-  llvm_unreachable("invalid enum");
+  auto Entry = Cache.try_emplace(S);
+  bool &Value = Entry.first->getValue();
+  // If the entry was just inserted, determine its required value.
+  if (Entry.second)
+Value = GlobList::contains(S);
+  return Value;
 }
 
 } // namespace tidy


Index: clang-tools-extra/clang-tidy/GlobList.h
===
--- clang-tools-extra/clang-tidy/GlobList.h
+++ clang-tools-extra/clang-tidy/GlobList.h
@@ -59,8 +59,7 @@
   bool contains(StringRef S) const override;
 
 private:
-  enum Tristate { None, Yes, No };
-  mutable llvm::StringMap Cache;
+  mutable llvm::StringMap Cache;
 };
 
 } // namespace tidy
Index: clang-tools-extra/clang-tidy/GlobList.cpp
===
--- clang-tools-extra/clang-tidy/GlobList.cpp
+++ clang-tools-extra/clang-tidy/GlobList.cpp
@@ -65,16 +65,12 @@
 }
 
 bool CachedGlobList::contains(StringRef S) const {
-  switch (auto &Result = Cache[S]) {
-  case Yes:
-return true;
-  case No:
-return false;
-  case None:
-Result = GlobList::contains(S) ? Yes : No;
-return Result == Yes;
-  }
-  llvm_unreachable("invalid enum");
+  auto Entry = Cache.try_emplace(S);
+  bool &Value = Entry.first->getValue();
+  // If the entry was just inserted, determine its required value.
+  if (Entry.second)
+Value = GlobList::contains(S);
+  return Value;
 }
 
 } // namespace tidy
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D120359: [clang-format][NFC] Remove redundant semi

2022-02-23 Thread Owen Pan via Phabricator via cfe-commits
owenpan requested changes to this revision.
owenpan added a comment.
This revision now requires changes to proceed.

Oops! For some reason, I thought the patch was //removing// the semi. See also 
D117301 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120359

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


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

2022-02-23 Thread Shreyas via Phabricator via cfe-commits
SAtacker updated this revision to Diff 410736.
SAtacker marked an inline comment as done.
SAtacker added a comment.

Squash commits D120385 , D120387 
 into D120331 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120331

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


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


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

[PATCH] D120333: [NFC][Lexer] Make access to LangOpts more consistent

2022-02-23 Thread serge via Phabricator via cfe-commits
serge-sans-paille added a comment.

I don't object to the change but it may me wonder if there would be a way to 
remove the apparent redundancy in the API here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120333

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


[PATCH] D119077: clangd SemanticHighlighting: added support for highlighting overloaded operators

2022-02-23 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

In D119077#3337107 , @nridge wrote:

> 1. The AST nodes that reference operator names should store source ranges 
> associated with the operator names, such that we shouldn't need to do 
> token-by-token manipulation. For example, 
> `functionDecl->getNameInfo().getCXXOperatorNameRange()`.

Fleshing this out a bit more:

- For `FunctionDecl`, `getNameInfo().getCXXOperatorNameRange()` is almost the 
right thing, but it excludes the `operator` keyword itself. We know 
`getLocation()` was giving us the location of the `operator` keyword, so we can 
construct the source range we want as `SourceRange(getLocation(), 
getNameInfo().getCXXOperatorNameRange().getEnd())`.
- For `DeclRefExpr`, we can do the same thing, using 
`DeclRefExpr::getNameInfo()`.
- For `MemberExpr`, same thing using `MemberExpr::getMemberNameInfo()` (and 
`getMemberLoc()` as the start of the range).
- For `CXXOperatorCallExpr`, it seems to only handle single-token cases so we 
should be good to continue using just `getOperatorLoc()`

I believe that should allow us to avoid token manipulation altogether.

> 2. [...] would it make sense to handle the **single-token** cases with 
> `findExplicitReferences()`? Or would that just end up splitting the logic / 
> duplicating code more?

Thinking more about this, I don't think it would make sense. For example, it's 
not the case that all //references// to overloaded operators could be handled 
by `findExplicitReferences()` (there are multi-token reference cases like 
explicit operator calls). So, let's just keep using `CollectExtraHighlightings` 
for all cases here.




Comment at: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp:815
+  $LocalVariable[[foo]].$Method[[operator()]]();
+  $LocalVariable[[foo]].$Method[[operator<<]](1);
+

I'm going to suggest that we exercise a few more implicit-call cases:
  * single-token, e.g. `foo << 1`
  * `operator()`, e.g. `foo()`
  * `operator[]`, e.g. `foo[1]`

(Very interestingly, in the implicit `()` and `[]` cases, the opening one seems 
to be colored by `VisitDeclRefExpr` but the closing one by 
`VisitCXXOperatorCallExpr`. Not quite sure why that is.)


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

https://reviews.llvm.org/D119077

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


[PATCH] D120310: [clang][analyzer] Add modeling of 'errno' (work-in-progress).

2022-02-23 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h:767-768
s->getType()->isBlockPointerType());
-assert(isa(sreg) || isa(sreg));
+assert(isa(sreg) || isa(sreg) ||
+   isa(sreg));
   }

steakhal wrote:
> At this point, I'm not even sure if we should assert any of these.
I mean, ideally this should be just `UnknownSpaceRegion`. For everything else 
we should have made a fresh `MemRegion` class. It is absurd that the same 
numeric address value (represented the symbol `s`) can correspond to two (now 
three) different locations in memory.



Comment at: clang/lib/StaticAnalyzer/Checkers/Errno.h:24-26
+/// Returns if modeling of 'errno' is available.
+/// If not, the other functions here should not be used.
+bool isErrnoAvailable(ProgramStateRef State);

steakhal wrote:
> I don't think we need this.
> In `getErrnoValue()` we should simply return `UnknownVal` if we don't have 
> 'errno.
> And in `setErrnoValue()` we should return the incoming `State` unmodified.
> 
> THat being said, only a top-level `Check::BeginFunction` callback could see 
> an 'errno' uninitialized, which I don't think is a real issue.
> All the rest of the callbacks would run after it's initialized, thus would 
> behave as expected.
> And in case the translation unit doesn't have nor 'errno' variable nor 
> 'errno_location_ish' functions, ignoring these `set/get` functions is 
> actually the expected behavior.
> 
> Having to check `isErrnoAvailable()` would be really an anti-pattern.
`UnknownVal` implies that it's an actual value but we don't know which one. If 
the value doesn't exist we shouldn't use it. And if the user doesn't include 
the appropriate header then the value really doesn't exist in the translation 
unit. So flavor-wise I think we shouldn't use `UnknownVal` here; I'd rather 
have an `Optional`.

Other than that, yeah, I think this is a good suggestion.



Comment at: clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp:32
+// FIXME: Is there a system where it is not called "errno" but is a variable?
+const char *ErrnoVarName = "errno";
+// Names of functions that return a location of the "errno" value.

steakhal wrote:
> Why don't you use `StringRef` here as well?
There's [[ 
https://llvm.org/docs/CodingStandards.html#do-not-use-static-constructors | 
that rule against static constructors/destructors ]]. We should use a lot of 
`constexpr` in these situations and/or try to turn these structures into plain 
C arrays as much as possible.



Comment at: clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp:66
+
+void ErrnoChecker::checkBeginFunction(CheckerContext &C) const {
+  if (!C.inTopFrame())

steakhal wrote:
> I would expect a comment stating that:
> - We inspect if we have a VarDecl naming "errno", it returns that Decl.
> - Otherwise, it will look for some common `errno_location` function names and 
> return that Decl. 
Ok so the first part of the function (identifying how the system headers 
represent `errno`) depends entirely on the AST right? In this case you can 
probably perform the AST scan only once during 
`checkASTDecl` and stash the result in a global variable. 
It shouldn't be re-run on every analysis. So whatever you do with 
`isErrnoAvailable()`, it shouldn't accept `ProgramStateRef` at all, it can 
simply query that global variable. You'll still need the state trait because 
`SVal` objects only make sense within a single analysis but the AST scan can be 
made only once.



Comment at: clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp:134
+const SymbolConjured *Sym =
+SVB.conjureSymbol(nullptr, C.getLocationContext(), ACtx.IntTy, 1);
+

steakhal wrote:
> 
This is literally the first step of the analysis. The block count is //known//.

What I really want to see here is a non-trivial custom tag (i.e., the `const 
void *symbolTag` parameter on some of the overloads of `conjureSymbolVal()`) to 
make sure this symbol isn't treated as a duplicate of any other symbol some 
other checker conjures initially. Like all tags, you can initialize it with 
some address of some checker-static variable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120310

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


[PATCH] D120394: [asan] Allow -fsanitize-address-globals-dead-stripping with -fno-data-sections for ELF

2022-02-23 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay created this revision.
MaskRay added reviewers: Sanitizers, eugenis, kstoimenov, vitalybuka.
Herald added a subscriber: ormris.
MaskRay requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

-fdata-sections decides whether global variables go into different sections.
This is orthogonal to whether we place their metadata (`.data` or 
`asan_globals`) into different sections.

With -fno-data-sections, `-fsanitize-address-globals-dead-stripping` can still:

- deduplicate COMDAT `asan.module_ctor` and `asan.module_dtor`
- (with ld --gc-sections): discard `asan_globals` sections and associated 
unreferenced global variables

Similar to c7b90947bd0179d914fea56b52be545c8f60f20a for PE/COFF.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120394

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/test/CodeGen/asan-globals-gc.cpp
  clang/test/CodeGen/asan-no-globals-no-comdat.cpp


Index: clang/test/CodeGen/asan-no-globals-no-comdat.cpp
===
--- clang/test/CodeGen/asan-no-globals-no-comdat.cpp
+++ clang/test/CodeGen/asan-no-globals-no-comdat.cpp
@@ -1,8 +1,7 @@
 // Test that on Linux asan constructor is placed in a comdat iff globals-gc is 
on.
 // Even if there are no globals in the module.
 
-// RUN: %clang_cc1 -fsanitize=address 
-fsanitize-address-globals-dead-stripping -emit-llvm -o - -triple x86_64-linux 
%s | FileCheck %s --check-prefix=WITHOUT-GC
-// RUN: %clang_cc1 -fsanitize=address 
-fsanitize-address-globals-dead-stripping -fdata-sections -emit-llvm -o - 
-triple x86_64-linux %s | FileCheck %s --check-prefix=WITH-GC
+// RUN: %clang_cc1 -fsanitize=address 
-fsanitize-address-globals-dead-stripping -emit-llvm -o - -triple x86_64-linux 
%s | FileCheck %s --check-prefix=WITH-GC
 // RUN: %clang_cc1 -fsanitize=address 
-fsanitize-address-globals-dead-stripping -fno-integrated-as -fdata-sections 
-emit-llvm -o - -triple x86_64-linux %s | FileCheck %s --check-prefix=WITHOUT-GC
 // RUN: %clang_cc1 -fsanitize=address 
-fsanitize-address-globals-dead-stripping -fno-integrated-as -emit-llvm -o - 
-triple x86_64-linux %s | FileCheck %s --check-prefix=WITHOUT-GC
 // RUN: %clang_cc1 -fsanitize=address -fdata-sections -emit-llvm -o - -triple 
x86_64-linux %s | FileCheck %s --check-prefix=WITHOUT-GC
Index: clang/test/CodeGen/asan-globals-gc.cpp
===
--- clang/test/CodeGen/asan-globals-gc.cpp
+++ clang/test/CodeGen/asan-globals-gc.cpp
@@ -1,5 +1,4 @@
-// RUN: %clang_cc1 -fsanitize=address 
-fsanitize-address-globals-dead-stripping -emit-llvm -o - -triple x86_64-linux 
%s | FileCheck %s --check-prefix=WITHOUT-GC
-// RUN: %clang_cc1 -fsanitize=address 
-fsanitize-address-globals-dead-stripping -fdata-sections -emit-llvm -o - 
-triple x86_64-linux %s | FileCheck %s --check-prefix=WITH-GC
+// RUN: %clang_cc1 -fsanitize=address 
-fsanitize-address-globals-dead-stripping -emit-llvm -o - -triple x86_64-linux 
%s | FileCheck %s --check-prefix=WITH-GC
 // RUN: %clang_cc1 -fsanitize=address 
-fsanitize-address-globals-dead-stripping -fno-integrated-as -fdata-sections 
-emit-llvm -o - -triple x86_64-linux %s | FileCheck %s --check-prefix=WITHOUT-GC
 // RUN: %clang_cc1 -fsanitize=address 
-fsanitize-address-globals-dead-stripping -fno-integrated-as -emit-llvm -o - 
-triple x86_64-linux %s | FileCheck %s --check-prefix=WITHOUT-GC
 // RUN: %clang_cc1 -fsanitize=address -fdata-sections -emit-llvm -o - -triple 
x86_64-linux %s | FileCheck %s --check-prefix=WITHOUT-GC
Index: clang/lib/CodeGen/BackendUtil.cpp
===
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -281,7 +281,7 @@
   case Triple::COFF:
 return true;
   case Triple::ELF:
-return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
+return !CGOpts.DisableIntegratedAS;
   case Triple::GOFF:
 llvm::report_fatal_error("ASan not implemented for GOFF");
   case Triple::XCOFF:


Index: clang/test/CodeGen/asan-no-globals-no-comdat.cpp
===
--- clang/test/CodeGen/asan-no-globals-no-comdat.cpp
+++ clang/test/CodeGen/asan-no-globals-no-comdat.cpp
@@ -1,8 +1,7 @@
 // Test that on Linux asan constructor is placed in a comdat iff globals-gc is on.
 // Even if there are no globals in the module.
 
-// RUN: %clang_cc1 -fsanitize=address -fsanitize-address-globals-dead-stripping -emit-llvm -o - -triple x86_64-linux %s | FileCheck %s --check-prefix=WITHOUT-GC
-// RUN: %clang_cc1 -fsanitize=address -fsanitize-address-globals-dead-stripping -fdata-sections -emit-llvm -o - -triple x86_64-linux %s | FileCheck %s --check-prefix=WITH-GC
+// RUN: %clang_cc1 -fsanitize=address -fsanitize-address-globals-dead-stripping -emit-llvm -o - -triple x86_64-linux %s | FileCheck %s --check-prefix=WITH-GC
 // RUN: %clang_cc1 -fsanitize=address

[PATCH] D120395: [X86] Prohibit arithmatic operations on type `__bfloat16`

2022-02-23 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei created this revision.
pengfei added reviewers: skan, RKSimon, craig.topper, FreddyYe, LuoYuanke.
pengfei requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

`__bfloat16` is defined as X86 specific type that represents the brain
floating-point format. It is only usable with X86 intrinsics. Arithmatic
operations with this type need to be forbidden.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120395

Files:
  clang/lib/Headers/avx512bf16intrin.h
  clang/lib/Headers/avx512vlbf16intrin.h
  clang/test/CodeGen/X86/avx512bf16-error.c


Index: clang/test/CodeGen/X86/avx512bf16-error.c
===
--- /dev/null
+++ clang/test/CodeGen/X86/avx512bf16-error.c
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -ffreestanding -triple 
x86_64-linux-pc %s
+
+// expected-error@+1 3 {{unknown type name '__bfloat16'}}
+__bfloat16 foo(__bfloat16 a, __bfloat16 b) {
+  return a + b;
+}
+
+#include 
+
+// expected-error@+2 {{invalid operands to binary expression ('__bfloat16' 
(aka 'struct __bfloat16_s') and '__bfloat16')}}
+__bfloat16 bar(__bfloat16 a, __bfloat16 b) {
+  return a + b;
+}
Index: clang/lib/Headers/avx512vlbf16intrin.h
===
--- clang/lib/Headers/avx512vlbf16intrin.h
+++ clang/lib/Headers/avx512vlbf16intrin.h
@@ -415,9 +415,10 @@
 ///and fraction field is truncated to 7 bits.
 static __inline__ __bfloat16 __DEFAULT_FN_ATTRS128 _mm_cvtness_sbh(float __A) {
   __v4sf __V = {__A, 0, 0, 0};
-  __v8hi __R = __builtin_ia32_cvtneps2bf16_128_mask(
+  __v8hi __R1 = __builtin_ia32_cvtneps2bf16_128_mask(
   (__v4sf)__V, (__v8hi)_mm_undefined_si128(), (__mmask8)-1);
-  return __R[0];
+  __bfloat16 __R2 = {__R1[0]};
+  return __R2;
 }
 
 /// Convert Packed BF16 Data to Packed float Data.
Index: clang/lib/Headers/avx512bf16intrin.h
===
--- clang/lib/Headers/avx512bf16intrin.h
+++ clang/lib/Headers/avx512bf16intrin.h
@@ -15,7 +15,14 @@
 
 typedef short __m512bh __attribute__((__vector_size__(64), __aligned__(64)));
 typedef short __m256bh __attribute__((__vector_size__(32), __aligned__(32)));
-typedef unsigned short __bfloat16;
+
+/// \typedef __bfloat16
+///A target specific type to represent the storage only brain 
floating-point
+///format type. Define through structure to explicitly prohibit any
+///arithmatic operations.
+typedef struct __bfloat16_s {
+  short _Value;
+} __bfloat16;
 
 #define __DEFAULT_FN_ATTRS512 \
   __attribute__((__always_inline__, __nodebug__, __target__("avx512bf16"), \
@@ -34,7 +41,7 @@
 /// \returns A float data whose sign field and exponent field keep unchanged,
 ///and fraction field is extended to 23 bits.
 static __inline__ float __DEFAULT_FN_ATTRS _mm_cvtsbh_ss(__bfloat16 __A) {
-  return __builtin_ia32_cvtsbf162ss_32(__A);
+  return __builtin_ia32_cvtsbf162ss_32(__A._Value);
 }
 
 /// Convert Two Packed Single Data to One Packed BF16 Data.


Index: clang/test/CodeGen/X86/avx512bf16-error.c
===
--- /dev/null
+++ clang/test/CodeGen/X86/avx512bf16-error.c
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -ffreestanding -triple x86_64-linux-pc %s
+
+// expected-error@+1 3 {{unknown type name '__bfloat16'}}
+__bfloat16 foo(__bfloat16 a, __bfloat16 b) {
+  return a + b;
+}
+
+#include 
+
+// expected-error@+2 {{invalid operands to binary expression ('__bfloat16' (aka 'struct __bfloat16_s') and '__bfloat16')}}
+__bfloat16 bar(__bfloat16 a, __bfloat16 b) {
+  return a + b;
+}
Index: clang/lib/Headers/avx512vlbf16intrin.h
===
--- clang/lib/Headers/avx512vlbf16intrin.h
+++ clang/lib/Headers/avx512vlbf16intrin.h
@@ -415,9 +415,10 @@
 ///and fraction field is truncated to 7 bits.
 static __inline__ __bfloat16 __DEFAULT_FN_ATTRS128 _mm_cvtness_sbh(float __A) {
   __v4sf __V = {__A, 0, 0, 0};
-  __v8hi __R = __builtin_ia32_cvtneps2bf16_128_mask(
+  __v8hi __R1 = __builtin_ia32_cvtneps2bf16_128_mask(
   (__v4sf)__V, (__v8hi)_mm_undefined_si128(), (__mmask8)-1);
-  return __R[0];
+  __bfloat16 __R2 = {__R1[0]};
+  return __R2;
 }
 
 /// Convert Packed BF16 Data to Packed float Data.
Index: clang/lib/Headers/avx512bf16intrin.h
===
--- clang/lib/Headers/avx512bf16intrin.h
+++ clang/lib/Headers/avx512bf16intrin.h
@@ -15,7 +15,14 @@
 
 typedef short __m512bh __attribute__((__vector_size__(64), __aligned__(64)));
 typedef short __m256bh __attribute__((__vector_size__(32), __aligned__(32)));
-typedef unsigned short __bfloat16;
+
+/// \typedef __bfloat16
+///A target specific type to represent the storage only brain floating-point
+///format type. Define through structure to explicitly prohibit any
+///a

[PATCH] D120334: [NFC][Lexer] Use more appropriate LangOptionsBase type for Lexer::LangOpts

2022-02-23 Thread serge via Phabricator via cfe-commits
serge-sans-paille added a comment.

A small local test hints that using a ``SmallVector`` instead of a 
``std::vector`` also fixes the assembly bloat. I don't know if it's worth 
considering as an alternative or  as an extra step.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120334

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


[PATCH] D113319: [clang-format] Improve require and concept handling

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

@HazardyKnusperkeks, forget my previous comment, I think I found what changed.
Before, the `*` was annotated twice, first as a BinaryOperator, then, on a 
second run, it was correctly annotated as a UnaryOperator.
In this revision you whitelisted BinaryOperator in `resetTokenMetadata`, so its 
type is determined once only.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113319

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


[PATCH] D119061: [Clang] noinline call site attribute

2022-02-23 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a comment.

ping


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

https://reviews.llvm.org/D119061

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


[PATCH] D120397: [C++20] [Modules] Make the linkage consistent for template and its specialization

2022-02-23 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu created this revision.
ChuanqiXu added reviewers: urnathan, iains, rsmith, aaron.ballman, erichkeane.
ChuanqiXu added a project: clang.
ChuanqiXu requested review of this revision.
Herald added a subscriber: cfe-commits.

Before the patch, the compiler would crash for the test due to inconsistent 
linkage.

This patch tries to avoid it by make the linkage consistent for template and 
its specialization. After the patch, the behavior of compiler would be 
partially correct for the case.
The correct one is:

  export template
  void f() {}
  
  template<>
  void f() {}

In this case, the linkage for both declaration should be external (the wording 
I get by consulting in WG21 is "the linkage for name `f` should be external").

And for the case:

  template
  void f() {}
  
  export template<>
  void f() {}

Compiler should reject it. This isn't done now. I marked it as FIXME in the 
test. After all, this patch would stop a crash.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120397

Files:
  clang/lib/AST/Decl.cpp
  clang/test/Modules/inconsist-export-template.cpp


Index: clang/test/Modules/inconsist-export-template.cpp
===
--- /dev/null
+++ clang/test/Modules/inconsist-export-template.cpp
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 -std=c++20 %s -fsyntax-only -verify
+// expected-no-diagnostics
+export module m;
+export template 
+void f() {
+
+}
+
+template <>
+void f() {
+
+}
+
+template 
+void f1() {
+
+}
+
+// FIXME: We should reject following specialization,
+// since it tries to export a name which is already introduced.
+export template <>
+void f1() {
+
+}
+
+export template
+class C {
+
+};
+
+template<>
+class C {
+
+};
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -391,11 +391,18 @@
   bool considerVisibility =
 shouldConsiderTemplateVisibility(fn, specInfo);
 
-  // Merge information from the template parameters.
   FunctionTemplateDecl *temp = specInfo->getTemplate();
-  LinkageInfo tempLV =
+
+  // Merge information from the template declaration.
+  LinkageInfo tempLV = getLVForDecl(temp, computation);
+  // The linkage of the specialization should be consistent with the
+  // template declaration.
+  LV.setLinkage(tempLV.getLinkage());
+
+  // Merge information from the template parameters.
+  LinkageInfo paramsLV =
 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
-  LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
+  LV.mergeMaybeWithVisibility(paramsLV, considerVisibility);
 
   // Merge information from the template arguments.
   const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;


Index: clang/test/Modules/inconsist-export-template.cpp
===
--- /dev/null
+++ clang/test/Modules/inconsist-export-template.cpp
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 -std=c++20 %s -fsyntax-only -verify
+// expected-no-diagnostics
+export module m;
+export template 
+void f() {
+
+}
+
+template <>
+void f() {
+
+}
+
+template 
+void f1() {
+
+}
+
+// FIXME: We should reject following specialization,
+// since it tries to export a name which is already introduced.
+export template <>
+void f1() {
+
+}
+
+export template
+class C {
+
+};
+
+template<>
+class C {
+
+};
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -391,11 +391,18 @@
   bool considerVisibility =
 shouldConsiderTemplateVisibility(fn, specInfo);
 
-  // Merge information from the template parameters.
   FunctionTemplateDecl *temp = specInfo->getTemplate();
-  LinkageInfo tempLV =
+
+  // Merge information from the template declaration.
+  LinkageInfo tempLV = getLVForDecl(temp, computation);
+  // The linkage of the specialization should be consistent with the
+  // template declaration.
+  LV.setLinkage(tempLV.getLinkage());
+
+  // Merge information from the template parameters.
+  LinkageInfo paramsLV =
 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
-  LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
+  LV.mergeMaybeWithVisibility(paramsLV, considerVisibility);
 
   // Merge information from the template arguments.
   const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D113319: [clang-format] Improve require and concept handling

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

Yep, confirmed, but I don't know how to fix it.
Just removing `TT_BinaryOperator` from `resetTokenMetadata` provokes these 
failures:

  [  FAILED  ] FormatTest.Concepts
  [  FAILED  ] FormatTest.RequiresClauses
  [  FAILED  ] TokenAnnotatorTest.UnderstandsRequiresClausesAndConcepts

Hopefully you have some idea how to fix it...

Oh, BTW, here's the test for the regression that Krasimir found:

  TEST_F(TokenAnnotatorTest, UnderstandsLoops) {
auto Tokens = annotate("while (p < q && *p == 0) {}");
EXPECT_EQ(Tokens.size(), 14u) << Tokens;
EXPECT_TOKEN(Tokens[6], tok::star, TT_UnaryOperator);
  }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113319

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


[PATCH] D119077: clangd SemanticHighlighting: added support for highlighting overloaded operators

2022-02-23 Thread Iannis de Zwart via Phabricator via cfe-commits
iannisdezwart added a comment.

Thank you for the comment, it's very helpful.

I didn't know exactly how to get all operator token locations and 
`getCXXOperatorNameRange()`.
This is going to be extremely helpful and will clean up the code to make it 
more readable.
Thank you for the detailed list of how to get the full operator name token 
location for each specific token type.

About your comment on the implicit calls to `operator[]` and `operator()`,
this was also a workaround. Do you have any idea how to get both parentheses 
from a single `DeclRefExpr`?
I researched this, but haven't yet found the answer.

I will try incorporating these changes today or tomorrow, if I can find time.


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

https://reviews.llvm.org/D119077

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


[clang] fa0a80e - Revert "Revert "[analyzer] Add failing test case demonstrating buggy taint propagation""

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

Author: Balazs Benics
Date: 2022-02-23T10:48:06+01:00
New Revision: fa0a80e017ebd58a71bdb4e4493bb022f80fe791

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

LOG: Revert "Revert "[analyzer] Add failing test case demonstrating buggy taint 
propagation""

This reverts commit b8ae323cca61dc1edcd36e9ae18c7e4c3d76d52e.

Let's try `REQUIRES: asserts`.

Added: 
clang/test/Analysis/taint-checker-callback-order-has-definition.c
clang/test/Analysis/taint-checker-callback-order-without-definition.c

Modified: 
clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
index e2209e3debfde..428778e6cfaa6 100644
--- a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
@@ -32,6 +32,8 @@
 #include 
 #include 
 
+#define DEBUG_TYPE "taint-checker"
+
 using namespace clang;
 using namespace ento;
 using namespace taint;
@@ -691,6 +693,13 @@ void GenericTaintChecker::checkPostCall(const CallEvent 
&Call,
   if (TaintArgs.isEmpty())
 return;
 
+  LLVM_DEBUG(for (ArgIdxTy I
+  : TaintArgs) {
+llvm::dbgs() << "PostCall<";
+Call.dump(llvm::dbgs());
+llvm::dbgs() << "> actually wants to taint arg index: " << I << '\n';
+  });
+
   for (ArgIdxTy ArgNum : TaintArgs) {
 // Special handling for the tainted return value.
 if (ArgNum == ReturnValueIndex) {
@@ -768,15 +777,25 @@ void GenericTaintRule::process(const GenericTaintChecker 
&Checker,
 
   /// Propagate taint where it is necessary.
   ForEachCallArg(
-  [this, &State, WouldEscape](ArgIdxTy I, const Expr *E, SVal V) {
-if (PropDstArgs.contains(I))
+  [this, &State, WouldEscape, &Call](ArgIdxTy I, const Expr *E, SVal V) {
+if (PropDstArgs.contains(I)) {
+  LLVM_DEBUG(llvm::dbgs() << "PreCall<"; Call.dump(llvm::dbgs());
+ llvm::dbgs()
+ << "> prepares tainting arg index: " << I << '\n';);
   State = State->add(I);
+}
 
 // TODO: We should traverse all reachable memory regions via the
 // escaping parameter. Instead of doing that we simply mark only the
 // referred memory region as tainted.
-if (WouldEscape(V, E->getType()))
+if (WouldEscape(V, E->getType())) {
+  LLVM_DEBUG(if (!State->contains(I)) {
+llvm::dbgs() << "PreCall<";
+Call.dump(llvm::dbgs());
+llvm::dbgs() << "> prepares tainting arg index: " << I << '\n';
+  });
   State = State->add(I);
+}
   });
 
   C.addTransition(State);

diff  --git a/clang/test/Analysis/taint-checker-callback-order-has-definition.c 
b/clang/test/Analysis/taint-checker-callback-order-has-definition.c
new file mode 100644
index 0..82943ad46fbd8
--- /dev/null
+++ b/clang/test/Analysis/taint-checker-callback-order-has-definition.c
@@ -0,0 +1,43 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core,alpha.security.taint \
+// RUN:   -mllvm -debug-only=taint-checker \
+// RUN:   2>&1 | FileCheck %s
+
+// REQUIRES: asserts
+// FIXME: We should not crash.
+// XFAIL: *
+
+struct _IO_FILE;
+typedef struct _IO_FILE FILE;
+FILE *fopen(const char *fname, const char *mode);
+
+void nested_call(void) {}
+
+char *fgets(char *s, int n, FILE *fp) {
+  nested_call();   // no-crash: we should not try adding taint to a 
non-existent argument.
+  return (char *)0;
+}
+
+void top(const char *fname, char *buf) {
+  FILE *fp = fopen(fname, "r");
+  // CHECK:  PreCall prepares tainting arg index: -1
+  // CHECK-NEXT: PostCall actually wants to taint arg 
index: -1
+
+  if (!fp)
+return;
+
+  (void)fgets(buf, 42, fp); // Trigger taint propagation.
+  // CHECK-NEXT: PreCall prepares tainting arg index: -1
+  // CHECK-NEXT: PreCall prepares tainting arg index: 0
+  // CHECK-NEXT: PreCall prepares tainting arg index: 1
+  // CHECK-NEXT: PreCall prepares tainting arg index: 2
+
+  // FIXME: We should propagate taint from PreCall -> PostCall.
+  // CHECK-NEXT: PostCall actually wants to taint arg index: -1
+  // CHECK-NEXT: PostCall actually wants to taint arg index: 0
+  // CHECK-NEXT: PostCall actually wants to taint arg index: 1
+  // CHECK-NEXT: PostCall actually wants to taint arg index: 2
+
+  // FIXME: We should not crash.
+  // CHECK: PLEASE submit a bug report
+}

diff  --git 
a/clang/test/Analysis/taint-checker-callback-order-without-definition.c 
b/clang/test/Analysis/taint-checker-callback-order-without-definition.c
new file mode 100644
index 0..dba23f367fd66
--- /dev/null
+++ b/clang/test/Analysis/taint-checker-callback-order-witho

[PATCH] D120236: [analyzer] Add more sources to Taint analysis

2022-02-23 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 410747.
gamesh411 marked 9 inline comments as done.
gamesh411 added a comment.

- s/getcw/getwd
- add gets_s
- remove getopt variants
- add realinkat
- discuss getnameinfo?
- rename tests
- update getnameinfo
- comment on source/propagator discrepancy
- update tests where 1 / tainted, and tainted cannot be 0
- renamed tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120236

Files:
  clang/docs/analyzer/checkers.rst
  clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
  clang/test/Analysis/taint-generic.c

Index: clang/test/Analysis/taint-generic.c
===
--- clang/test/Analysis/taint-generic.c
+++ clang/test/Analysis/taint-generic.c
@@ -45,8 +45,11 @@
 // CHECK-INVALID-ARG-SAME:that expects an argument number for propagation
 // CHECK-INVALID-ARG-SAME:rules greater or equal to -1
 
+typedef long long rsize_t;
+
 int scanf(const char *restrict format, ...);
 char *gets(char *str);
+char *gets_s(char *str, rsize_t n);
 int getchar(void);
 
 typedef struct _FILE FILE;
@@ -195,6 +198,12 @@
   system(str); // expected-warning {{Untrusted data is passed to a system call}}
 }
 
+void testGets_s(void) {
+  char str[50];
+  gets_s(str, 49);
+  system(str); // expected-warning {{Untrusted data is passed to a system call}}
+}
+
 void testTaintedBufferSize(void) {
   size_t ts;
   scanf("%zd", &ts);
@@ -341,15 +350,112 @@
 *(volatile int *) 0; // no-warning
 }
 
-int sprintf_is_not_a_source(char *buf, char *msg) {
+int testSprintf_is_not_a_source(char *buf, char *msg) {
   int x = sprintf(buf, "%s", msg); // no-warning
-  return 1 / x; // no-warning: 'sprintf' is not a taint source
+  return 1 / x;// no-warning: 'sprintf' is not a taint source
 }
 
-int sprintf_propagates_taint(char *buf, char *msg) {
+int testSprintf_propagates_taint(char *buf, char *msg) {
   scanf("%s", msg);
   int x = sprintf(buf, "%s", msg); // propagate taint!
-  return 1 / x; // expected-warning {{Division by a tainted value, possibly zero}}
+  return 1 / x;// expected-warning {{Division by a tainted value, possibly zero}}
+}
+
+int scanf_s(const char *format, ...);
+int testScanf_s_(int *out) {
+  scanf_s("%d", out);
+  return 1 / *out; // expected-warning {{Division by a tainted value, possibly zero}}
+}
+
+#define _IO_FILE FILE
+int _IO_getc(_IO_FILE *__fp);
+int test_IO_getc(_IO_FILE *fp) {
+  char c = _IO_getc(fp);
+  return 1 / c; // expected-warning {{Division by a tainted value, possibly zero}}
+}
+
+char *getcwd(char *buf, size_t size);
+int testGetcwd(char *buf, size_t size) {
+  char *c = getcwd(buf, size);
+  return system(c); // expected-warning {{Untrusted data is passed to a system call}}
+}
+
+char *getwd(char *buf);
+int testGetwd(char *buf) {
+  char *c = getwd(buf);
+  return system(c); // expected-warning {{Untrusted data is passed to a system call}}
+}
+
+typedef signed long long ssize_t;
+ssize_t readlink(const char *path, char *buf, size_t bufsiz);
+int testReadlink(char *path, char *buf, size_t bufsiz) {
+  ssize_t s = readlink(path, buf, bufsiz);
+  system(buf); // expected-warning {{Untrusted data is passed to a system call}}
+  // readlink never returns 0
+  return 1 / (s + 1); // expected-warning {{Division by a tainted value, possibly zero}}
+}
+
+ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz);
+int testReadlinkat(int dirfd, char *path, char *buf, size_t bufsiz) {
+  ssize_t s = readlinkat(dirfd, path, buf, bufsiz);
+  system(buf); // expected-warning {{Untrusted data is passed to a system call}}
+  // readlinkat never returns 0
+  return 1 / (s + 1); // expected-warning {{Division by a tainted value, possibly zero}}
+}
+
+char *get_current_dir_name(void);
+int testGet_current_dir_name() {
+  char *d = get_current_dir_name();
+  return system(d); // expected-warning {{Untrusted data is passed to a system call}}
+}
+
+int gethostname(char *name, size_t len);
+int testGethostname(char *name, size_t len) {
+  gethostname(name, len);
+  return system(name); // expected-warning {{Untrusted data is passed to a system call}}
+}
+
+struct sockaddr;
+typedef size_t socklen_t;
+int getnameinfo(const struct sockaddr *restrict addr, socklen_t addrlen,
+char *restrict host, socklen_t hostlen,
+char *restrict serv, socklen_t servlen, int flags);
+int testGetnameinfo(const struct sockaddr *restrict addr, socklen_t addrlen,
+char *restrict host, socklen_t hostlen,
+char *restrict serv, socklen_t servlen, int flags) {
+  getnameinfo(addr, addrlen, host, hostlen, serv, servlen, flags);
+
+  system(host);// expected-warning {{Untrusted data is passed to a system call}}
+  return system(serv); // expected-warning {{Untrusted data is passed to a system call}}
+}
+
+int get

[PATCH] D120236: [analyzer] Add more sources to Taint analysis

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



Comment at: clang/docs/analyzer/checkers.rst:2358
 Default sources defined by ``GenericTaintChecker``:
-``fdopen``, ``fopen``, ``freopen``, ``getch``, ``getchar``, 
``getchar_unlocked``, ``gets``, ``scanf``, ``socket``, ``wgetch``
+ ``_IO_getc``, ``fdopen``, ``fopen``, ``freopen``, ``get_current_dir_name``, 
``getch``, ``getchar``, ``getchar_unlocked``, ``getcw``, ``getcwd``, 
``getgroups``, ``gethostname``, ``getlogin``, ``getlogin_r``, ``getnameinfo``, 
``getopt``, ``getopt_long``, ``getopt_only``, ``gets``, ``getseuserbyname``, 
``readlink``, ``scanf``, ``scanf_s``, ``socket``, ``wgetch``
 

steakhal wrote:
> typo/dup?
> I cannot recognize the `getcw()` call. Could you please refer to the 
> specification or an instance where it was defined?
`getwd` is the right one instead of `getcw`



Comment at: clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp:546-548
   {{"gets"}, TR::Source({{0}, ReturnValueIndex})},
   {{"scanf"}, TR::Source({{}, 1})},
+  {{"scanf_s"}, TR::Source({{}, {1}})},

steakhal wrote:
> If we handle `gets`, `scanf`, we should also model the `*_s` versions as well.
> ```lang=C
> char *gets_s(char *s, rsize_t n);
> int scanf_s(const char *restrict format, ...);
> int fscanf_s(FILE *restrict stream, const char *restrict format, ...);
> int sscanf_s(const char *restrict s, const char *restrict format, ...);
> int vscanf_s(const char *restrict format, va_list arg);
> int vfscanf_s(FILE *restrict stream, const char *restrict format, va_list 
> arg);
> int vsscanf_s(const char *restrict s, const char *restrict format, va_list 
> arg);
> ```
I have added gets_s, and will add the _s variants for the others in the other 
patch that deals with the propagatorsj.



Comment at: clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp:550-552
+  {{"getopt"}, TR::Source({{ReturnValueIndex}})},
+  {{"getopt_long"}, TR::Source({{ReturnValueIndex}})},
+  {{"getopt_long_only"}, TR::Source({{ReturnValueIndex}})},

steakhal wrote:
> IMO these functions are highly domain-specific.
> On errors, they return specific/well-defined values e.g. `-1`, `'?'` or `':'`.
> That being said, the analyzer does not have this knowledge, thus it will 
> model these as `conjured` symbols.
> If these values were modeled as tainted, we would likely introduce the number 
> of false-positives regarding our limited capabilities of modeling the 
> function accurately.
> 
> tldr; I'm against these three rules; or alternatively prove that my concerns 
> are not issues on real code bases.
I  agree that the handling of these should be in another checker, I remember 
some false positives ( mainly uninteresting, typical "just won't fix" errors ) 
relating to `getopt`, and a domain-specific checker could be more appropriate 
here.
Removed them.



Comment at: clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp:556
+  {{"getwd"}, TR::Source({{0, ReturnValueIndex}})},
+  {{"readlink"}, TR::Source({{1, ReturnValueIndex}})},
+  {{"get_current_dir_name"}, TR::Source({{ReturnValueIndex}})},

steakhal wrote:
> We should check `readlinkat` as well.
Added



Comment at: clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp:559
+  {{"gethostname"}, TR::Source({{0}})},
+  {{"getnameinfo"}, TR::Source({{2, 4}})},
+  {{"getseuserbyname"}, TR::Source({{1, 2}})},

steakhal wrote:
> In what cases can this function introduce taint?
The getnameinfo converts from
```
struct sockaddr_in {
sa_family_tsin_family; /* address family: AF_INET */
in_port_t  sin_port;   /* port in network byte order */
struct in_addr sin_addr;   /* internet address */
};

/* Internet address */
struct in_addr {
uint32_t   s_addr; /* address in network byte order */
};
```
to hostname and servername strings.
One could argue that by crafting a specific IP address, that  is known to 
resolve to a specific hostname in the running environment could lead an 
attacker injecting a chosen (in some circumstances arbitrary) string into the 
code at the point of this function.

I know this is a bit contrived, and more on the cybersecurity side of things, 
so I am not sure whether to add this here, or add this in a specific checker, 
or just leave altogether. Please share your opinion about this.



Comment at: clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp:561
+  {{"getseuserbyname"}, TR::Source({{1, 2}})},
+  {{"getgroups"}, TR::Source({{1}})},
+  {{"getlogin"}, TR::Source({{ReturnValueIndex}})},

steakhal wrote:
> >On success, `getgroups()` returns the number of supplementary group IDs. On 
> >error, -1 is returned, and `errno` is set appropriately.
> 
> According to this, the return value index should be also tainted.
Added




Comm

[clang] 9d91e03 - [clang] CIndex.cpp - use cast<> instead of dyn_cast<> to avoid dereference of nullptr

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

Author: Simon Pilgrim
Date: 2022-02-23T10:09:44Z
New Revision: 9d91e03b7d075239483e9a5793e1e5db9152bdf1

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

LOG: [clang] CIndex.cpp - use cast<> instead of dyn_cast<> to avoid dereference 
of nullptr

The pointers are used immediately, so assert the cast is correct instead of 
returning nullptr

Added: 


Modified: 
clang/tools/libclang/CIndex.cpp

Removed: 




diff  --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index 53494ecc7ae9d..e77b85d63c53e 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -4010,7 +4010,7 @@ static const ExprEvalResult *evaluateExpr(Expr *expr, 
CXCursor C) {
   }
 
   if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
-const ImplicitCastExpr *I = dyn_cast(expr);
+const auto *I = cast(expr);
 auto *subExpr = I->getSubExprAsWritten();
 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
@@ -6740,8 +6740,8 @@ void clang_getDefinitionSpellingAndExtent(
 CXCursor C, const char **startBuf, const char **endBuf, unsigned 
*startLine,
 unsigned *startColumn, unsigned *endLine, unsigned *endColumn) {
   assert(getCursorDecl(C) && "CXCursor has null decl");
-  const FunctionDecl *FD = dyn_cast(getCursorDecl(C));
-  CompoundStmt *Body = dyn_cast(FD->getBody());
+  const auto *FD = cast(getCursorDecl(C));
+  const auto *Body = cast(FD->getBody());
 
   SourceManager &SM = FD->getASTContext().getSourceManager();
   *startBuf = SM.getCharacterData(Body->getLBracLoc());
@@ -8289,7 +8289,7 @@ unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor 
C, unsigned reserved) {
 return CXObjCPropertyAttr_noattr;
 
   unsigned Result = CXObjCPropertyAttr_noattr;
-  const ObjCPropertyDecl *PD = dyn_cast(getCursorDecl(C));
+  const auto *PD = cast(getCursorDecl(C));
   ObjCPropertyAttribute::Kind Attr = PD->getPropertyAttributesAsWritten();
 
 #define SET_CXOBJCPROP_ATTR(A) 
\
@@ -8317,7 +8317,7 @@ CXString clang_Cursor_getObjCPropertyGetterName(CXCursor 
C) {
   if (C.kind != CXCursor_ObjCPropertyDecl)
 return cxstring::createNull();
 
-  const ObjCPropertyDecl *PD = dyn_cast(getCursorDecl(C));
+  const auto *PD = cast(getCursorDecl(C));
   Selector sel = PD->getGetterName();
   if (sel.isNull())
 return cxstring::createNull();
@@ -8329,7 +8329,7 @@ CXString clang_Cursor_getObjCPropertySetterName(CXCursor 
C) {
   if (C.kind != CXCursor_ObjCPropertyDecl)
 return cxstring::createNull();
 
-  const ObjCPropertyDecl *PD = dyn_cast(getCursorDecl(C));
+  const auto *PD = cast(getCursorDecl(C));
   Selector sel = PD->getSetterName();
   if (sel.isNull())
 return cxstring::createNull();



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


[PATCH] D119720: [ARM] Pass for Cortex-A57 and Cortex-A72 Fused AES Erratum

2022-02-23 Thread Dave Green via Phabricator via cfe-commits
dmgreen added a comment.

I have a high level question regarding RDF, as I've not seen it used in many 
other places, so it may be under-tested on Arm systems at the moment. This 
currently, for all code, builds an rdf graph, analyze the rdf graph for a 
fairly rare instructions, then fixes up the code based on that.  It might be 
best to avoid the (possibly expensive?) rdf graph generation for the common 
case where the instructions are not present. Check that the instruction exists 
first.

It might then be simpler to just search back for the def of a register, 
considering in most code the instruction we are looking for should be fairly 
rare and we won't expect to need to find def's in bulk. That might be simpler 
overall, and avoid some of the difficulties of RDF.




Comment at: llvm/test/CodeGen/ARM/aes-erratum-fix.ll:49
+
+define <16 x i8> @aese_once_via_val(<16 x i8> %0, <16 x i8> %1) nounwind {
+; CHECK-FIX-NOSCHED-LABEL: aese_once_via_val:

Adding arm_aapcs_vfpcc will make the function "hardfp", which might be useful 
for testing inputs from argument that don't need to be passed via gpr regs.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119720

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


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

2022-02-23 Thread Konrad Wilhelm Kleine via Phabricator via cfe-commits
kwk created this revision.
kwk requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Analogous to https://reviews.llvm.org/D93758, this patch uses
`unsigned char` for all enums in `FormatStyle`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120398

Files:
  clang/include/clang/Format/Format.h


Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -105,7 +105,7 @@
   BracketAlignmentStyle AlignAfterOpenBracket;
 
   /// Different style for aligning array initializers.
-  enum ArrayInitializerAlignmentStyle {
+  enum ArrayInitializerAlignmentStyle : unsigned char {
 /// Align array column and left justify the columns e.g.:
 /// \code
 ///   struct test demo[] =
@@ -140,7 +140,7 @@
   /// ``AlignConsecutiveBitFields``), names in declarations (see
   /// ``AlignConsecutiveDeclarations``) or macro definitions (see
   /// ``AlignConsecutiveMacros``).
-  enum AlignConsecutiveStyle {
+  enum AlignConsecutiveStyle : unsigned char {
 ACS_None,
 ACS_Consecutive,
 ACS_AcrossEmptyLines,
@@ -1771,7 +1771,7 @@
   BraceWrappingFlags BraceWrapping;
 
   /// Different ways to break before concept declarations.
-  enum BreakBeforeConceptDeclarationsStyle {
+  enum BreakBeforeConceptDeclarationsStyle : unsigned char {
 /// Keep the template declaration line together with ``concept``.
 /// \code
 ///   template  concept C = ...;
@@ -1882,7 +1882,7 @@
   std::string CommentPragmas;
 
   /// Different specifiers and qualifiers alignment styles.
-  enum QualifierAlignmentStyle {
+  enum QualifierAlignmentStyle : unsigned char {
 /// Don't change specifiers/qualifiers to either Left or Right alignment
 /// (default).
 /// \code
@@ -3067,7 +3067,7 @@
   std::vector RawStringFormats;
 
   /// \brief The ``&`` and ``&&`` alignment style.
-  enum ReferenceAlignmentStyle {
+  enum ReferenceAlignmentStyle : unsigned char {
 /// Align reference like ``PointerAlignment``.
 RAS_Pointer,
 /// Align reference to the left.
@@ -3166,7 +3166,7 @@
   /// \brief The possible positions for the requires clause. The
   /// ``IndentRequires`` option is only used if the ``requires`` is put on the
   /// start of a line.
-  enum RequiresClausePositionStyle {
+  enum RequiresClausePositionStyle : unsigned char {
 /// Always put the ``requires`` clause on its own line.
 /// \code
 ///   template 
@@ -3245,7 +3245,7 @@
   RequiresClausePositionStyle RequiresClausePosition;
 
   /// \brief The style if definition blocks should be separated.
-  enum SeparateDefinitionStyle {
+  enum SeparateDefinitionStyle : unsigned char {
 /// Leave definition blocks as they are.
 SDS_Leave,
 /// Insert an empty line between definition blocks.


Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -105,7 +105,7 @@
   BracketAlignmentStyle AlignAfterOpenBracket;
 
   /// Different style for aligning array initializers.
-  enum ArrayInitializerAlignmentStyle {
+  enum ArrayInitializerAlignmentStyle : unsigned char {
 /// Align array column and left justify the columns e.g.:
 /// \code
 ///   struct test demo[] =
@@ -140,7 +140,7 @@
   /// ``AlignConsecutiveBitFields``), names in declarations (see
   /// ``AlignConsecutiveDeclarations``) or macro definitions (see
   /// ``AlignConsecutiveMacros``).
-  enum AlignConsecutiveStyle {
+  enum AlignConsecutiveStyle : unsigned char {
 ACS_None,
 ACS_Consecutive,
 ACS_AcrossEmptyLines,
@@ -1771,7 +1771,7 @@
   BraceWrappingFlags BraceWrapping;
 
   /// Different ways to break before concept declarations.
-  enum BreakBeforeConceptDeclarationsStyle {
+  enum BreakBeforeConceptDeclarationsStyle : unsigned char {
 /// Keep the template declaration line together with ``concept``.
 /// \code
 ///   template  concept C = ...;
@@ -1882,7 +1882,7 @@
   std::string CommentPragmas;
 
   /// Different specifiers and qualifiers alignment styles.
-  enum QualifierAlignmentStyle {
+  enum QualifierAlignmentStyle : unsigned char {
 /// Don't change specifiers/qualifiers to either Left or Right alignment
 /// (default).
 /// \code
@@ -3067,7 +3067,7 @@
   std::vector RawStringFormats;
 
   /// \brief The ``&`` and ``&&`` alignment style.
-  enum ReferenceAlignmentStyle {
+  enum ReferenceAlignmentStyle : unsigned char {
 /// Align reference like ``PointerAlignment``.
 RAS_Pointer,
 /// Align reference to the left.
@@ -3166,7 +3166,7 @@
   /// \brief The possible positions for the requires clause. The
   /// ``IndentRequires`` option is only used if the ``requires`` is put on the
   /// start of a line.
-  enum RequiresClausePositionStyle {
+  enum RequiresCl

[clang] 5a74e6a - [Modules] Add module structure output to -module-file-info.

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

Author: Iain Sandoe
Date: 2022-02-23T10:26:42Z
New Revision: 5a74e6a21c9520e0619c98a66815fc8b5117e321

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

LOG: [Modules] Add module structure output to -module-file-info.

It is useful to be able to visualise the C++20 modules content of a PCM file
both for inspection and for testing.  In particular, when adding more module
types to support C++20 Partitions and Header Units, we would like to be able
to confirm that the output PCM has the intended structure.

The existing scheme for dumping data is restricted to the content of the AST
file control block, which does not include structural data beyond imports.

The change here makes use of the AST unit that is set up by BeginSourceFile
to query for the information on the primary and sub-modules.  We can then
inspect each of these in turn, accounting for Global, Private, Imported and
Exported modules/fragments and then showing the sub-stucture of the main
module(s).

The disadvantage of this mechanism is that it has no easy method to control
the granularity of the output.  Perhaps more detailed inspection would be
better handled by a stand-alone module inspection tool.

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

Added: 
clang/test/Modules/cxx20-module-file-info.cpp

Modified: 
clang/lib/Frontend/FrontendActions.cpp

Removed: 




diff  --git a/clang/lib/Frontend/FrontendActions.cpp 
b/clang/lib/Frontend/FrontendActions.cpp
index ad2e6039477f8..baf3ac34db620 100644
--- a/clang/lib/Frontend/FrontendActions.cpp
+++ b/clang/lib/Frontend/FrontendActions.cpp
@@ -11,6 +11,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangStandard.h"
+#include "clang/Basic/Module.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Frontend/ASTConsumers.h"
 #include "clang/Frontend/CompilerInstance.h"
@@ -24,6 +25,7 @@
 #include "clang/Sema/TemplateInstCallback.h"
 #include "clang/Serialization/ASTReader.h"
 #include "clang/Serialization/ASTWriter.h"
+#include "clang/Serialization/ModuleFile.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
@@ -806,7 +808,25 @@ bool 
DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
   return true;
 }
 
+static StringRef ModuleKindName(Module::ModuleKind MK) {
+  switch (MK) {
+  case Module::ModuleMapModule:
+return "Module Map Module";
+  case Module::ModuleInterfaceUnit:
+return "Interface Unit";
+  case Module::ModulePartitionInterface:
+return "Partition Interface";
+  case Module::ModulePartitionImplementation:
+return "Partition Implementation";
+  case Module::GlobalModuleFragment:
+return "Global Module Fragment";
+  case Module::PrivateModuleFragment:
+return "Private Module Fragment";
+  }
+}
+
 void DumpModuleInfoAction::ExecuteAction() {
+  assert(isCurrentFileAST() && "dumping non-AST?");
   // Set up the output file.
   std::unique_ptr OutFile;
   StringRef OutputFileName = 
getCompilerInstance().getFrontendOpts().OutputFile;
@@ -827,8 +847,87 @@ void DumpModuleInfoAction::ExecuteAction() {
 
   Preprocessor &PP = getCompilerInstance().getPreprocessor();
   DumpModuleInfoListener Listener(Out);
-  HeaderSearchOptions &HSOpts =
-  PP.getHeaderSearchInfo().getHeaderSearchOpts();
+  HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
+
+  // The FrontendAction::BeginSourceFile () method loads the AST so that much
+  // of the information is already available and modules should have been
+  // loaded.
+
+  const LangOptions &LO = getCurrentASTUnit().getLangOpts();
+  if (LO.CPlusPlusModules && !LO.CurrentModule.empty()) {
+
+ASTReader *R = getCurrentASTUnit().getASTReader().get();
+unsigned SubModuleCount = R->getTotalNumSubmodules();
+serialization::ModuleFile &MF = R->getModuleManager().getPrimaryModule();
+Out << "  == C++20 Module structure ==\n";
+
+if (MF.ModuleName != LO.CurrentModule)
+  Out << "  Mismatched module names : " << MF.ModuleName << " and "
+  << LO.CurrentModule << "\n";
+
+struct SubModInfo {
+  unsigned Idx;
+  Module *Mod;
+  Module::ModuleKind Kind;
+  std::string &Name;
+  bool Seen;
+};
+std::map SubModMap;
+auto PrintSubMapEntry = [&](std::string Name, Module::ModuleKind Kind) {
+  Out << "" << ModuleKindName(Kind) << " '" << Name << "'";
+  auto I = SubModMap.find(Name);
+  if (I == SubModMap.end())
+Out << " was not found in the sub modules!\n";
+  else {
+I->second.Seen = true;
+Out << " is at index #" << I->second.Idx << "\n";
+  }
+};
+Module *Primary = nullptr;
+for (unsigned Idx = 0; Idx <= SubModu

[PATCH] D119823: [Modules] Add module structure output to -module-file-info.

2022-02-23 Thread Iain Sandoe 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 rG5a74e6a21c95: [Modules] Add module structure output to 
-module-file-info. (authored by iains).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119823

Files:
  clang/lib/Frontend/FrontendActions.cpp
  clang/test/Modules/cxx20-module-file-info.cpp

Index: clang/test/Modules/cxx20-module-file-info.cpp
===
--- /dev/null
+++ clang/test/Modules/cxx20-module-file-info.cpp
@@ -0,0 +1,64 @@
+// Test output from -module-file-info about C++20 modules.
+
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/mod-info-tu1.cpp \
+// RUN:  -o %t/A.pcm
+
+// RUN: %clang_cc1 -std=c++20 -module-file-info %t/A.pcm | FileCheck \
+// RUN:  --check-prefix=CHECK-A %s
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/mod-info-tu2.cpp \
+// RUN:  -o %t/B.pcm
+
+// RUN: %clang_cc1 -std=c++20 -module-file-info %t/B.pcm | FileCheck \
+// RUN:  --check-prefix=CHECK-B %s
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/mod-info-tu3.cpp \
+// RUN:  -fmodule-file=%t/A.pcm -fmodule-file=%t/B.pcm -o %t/Foo.pcm
+
+// RUN: %clang_cc1 -std=c++20 -module-file-info %t/Foo.pcm | FileCheck \
+// RUN:  --check-prefix=CHECK-FOO %s
+
+// expected-no-diagnostics
+
+//--- mod-info-tu1.cpp
+export module A;
+
+void a();
+
+// CHECK-A: == C++20
+// CHECK-A-NEXT: Interface Unit 'A' is the Primary Module at index #1
+
+//--- mod-info-tu2.cpp
+export module B;
+
+void b();
+
+// CHECK-B: == C++20
+// CHECK-B-NEXT: Interface Unit 'B' is the Primary Module at index #1
+
+//--- mod-info-tu3.cpp
+module;
+
+export module Foo;
+
+import A;
+export import B;
+
+namespace hello {
+export void say(const char *);
+}
+
+void foo() {}
+
+// CHECK-FOO: == C++20
+// CHECK-FOO-NEXT:  Interface Unit 'Foo' is the Primary Module at index #3
+// CHECK-FOO-NEXT:   Sub Modules:
+// CHECK-FOO-NEXT:Global Module Fragment '' is at index #4
+// CHECK-FOO-NEXT:   Imports:
+// CHECK-FOO-NEXT:Interface Unit 'A' is at index #1
+// CHECK-FOO-NEXT:   Exports:
+// CHECK-FOO-NEXT:Interface Unit 'B' is at index #2
Index: clang/lib/Frontend/FrontendActions.cpp
===
--- clang/lib/Frontend/FrontendActions.cpp
+++ clang/lib/Frontend/FrontendActions.cpp
@@ -11,6 +11,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangStandard.h"
+#include "clang/Basic/Module.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Frontend/ASTConsumers.h"
 #include "clang/Frontend/CompilerInstance.h"
@@ -24,6 +25,7 @@
 #include "clang/Sema/TemplateInstCallback.h"
 #include "clang/Serialization/ASTReader.h"
 #include "clang/Serialization/ASTWriter.h"
+#include "clang/Serialization/ModuleFile.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
@@ -806,7 +808,25 @@
   return true;
 }
 
+static StringRef ModuleKindName(Module::ModuleKind MK) {
+  switch (MK) {
+  case Module::ModuleMapModule:
+return "Module Map Module";
+  case Module::ModuleInterfaceUnit:
+return "Interface Unit";
+  case Module::ModulePartitionInterface:
+return "Partition Interface";
+  case Module::ModulePartitionImplementation:
+return "Partition Implementation";
+  case Module::GlobalModuleFragment:
+return "Global Module Fragment";
+  case Module::PrivateModuleFragment:
+return "Private Module Fragment";
+  }
+}
+
 void DumpModuleInfoAction::ExecuteAction() {
+  assert(isCurrentFileAST() && "dumping non-AST?");
   // Set up the output file.
   std::unique_ptr OutFile;
   StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
@@ -827,8 +847,87 @@
 
   Preprocessor &PP = getCompilerInstance().getPreprocessor();
   DumpModuleInfoListener Listener(Out);
-  HeaderSearchOptions &HSOpts =
-  PP.getHeaderSearchInfo().getHeaderSearchOpts();
+  HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
+
+  // The FrontendAction::BeginSourceFile () method loads the AST so that much
+  // of the information is already available and modules should have been
+  // loaded.
+
+  const LangOptions &LO = getCurrentASTUnit().getLangOpts();
+  if (LO.CPlusPlusModules && !LO.CurrentModule.empty()) {
+
+ASTReader *R = getCurrentASTUnit().getASTReader().get();
+unsigned SubModuleCount = R->getTotalNumSubmodules();
+serialization::ModuleFile &MF = R->getModuleManager().getPrimaryModule();
+Out << "  == C++20 Module structure ==\n";
+
+if (MF.ModuleName != LO.CurrentModule)
+  Out << "  Mismatched module names : " << MF.ModuleName << " and "
+  << LO.CurrentModule << "\n";

[PATCH] D120334: [NFC][Lexer] Use more appropriate LangOptionsBase type for Lexer::LangOpts

2022-02-23 Thread serge via Phabricator via cfe-commits
serge-sans-paille added a comment.

https://llvm-compile-time-tracker.com/compare.php?from=79c9072dc009693477242bc1347a2a6c3e419423&to=702bdad5179ebb90c8d8a16c800ffd1b3c44744d&stat=instructions
 << indeed a lot of green there!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120334

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


[PATCH] D120333: [NFC][Lexer] Make access to LangOpts more consistent

2022-02-23 Thread Dawid Jurczak via Phabricator via cfe-commits
yurai007 added a comment.

Thank you all for review!

In D120333#3339730 , 
@serge-sans-paille wrote:

> I don't object to the change but it may me wonder if there would be a way to 
> remove the apparent redundancy in the API here?

If you don't mind let me address getLangOpts() removal in follow-up change 
since this one as it is already got LG.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120333

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


[clang] 169e1ab - Revert "[clang][dataflow] Add support for global storage values"

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

Author: Stanislav Gatev
Date: 2022-02-23T10:32:17Z
New Revision: 169e1aba55bed9f7ffa000f9f170ab2defbc40b2

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

LOG: Revert "[clang][dataflow] Add support for global storage values"

This reverts commit 7ea103de140b59a64fc884fa90afd2213619384d.

Added: 


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

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index bab20418a016a..af613c95bb8dc 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -49,11 +49,6 @@ enum class SkipPast {
 };
 
 /// Holds the state of the program (store and heap) at a given program point.
-///
-/// WARNING: Symbolic values that are created by the environment for static
-/// local and global variables are not currently invalidated on function calls.
-/// This is unsound and should be taken into account when designing dataflow
-/// analyses.
 class Environment {
 public:
   /// Supplements `Environment` with non-standard comparison and join

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index f20c747c56c2d..eca58b313761b 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -22,7 +22,6 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/Support/ErrorHandling.h"
-#include 
 #include 
 #include 
 
@@ -57,55 +56,10 @@ static bool equivalentValues(QualType Type, Value *Val1, 
Value *Val2,
   return Model.compareEquivalent(Type, *Val1, *Val2);
 }
 
-/// Initializes a global storage value.
-static void initGlobalVar(const VarDecl &D, Environment &Env) {
-  if (!D.hasGlobalStorage() ||
-  Env.getStorageLocation(D, SkipPast::None) != nullptr)
-return;
-
-  auto &Loc = Env.createStorageLocation(D);
-  Env.setStorageLocation(D, Loc);
-  if (auto *Val = Env.createValue(D.getType()))
-Env.setValue(Loc, *Val);
-}
-
-/// Initializes a global storage value.
-static void initGlobalVar(const Decl &D, Environment &Env) {
-  if (auto *V = dyn_cast(&D))
-initGlobalVar(*V, Env);
-}
-
-/// Initializes global storage values that are declared or referenced from
-/// sub-statements of `S`.
-// FIXME: Add support for resetting globals after function calls to enable
-// the implementation of sound analyses.
-static void initGlobalVars(const Stmt &S, Environment &Env) {
-  for (auto *Child : S.children()) {
-if (Child != nullptr)
-  initGlobalVars(*Child, Env);
-  }
-
-  if (auto *DS = dyn_cast(&S)) {
-if (DS->isSingleDecl()) {
-  const auto &D = *cast(DS->getSingleDecl());
-  initGlobalVar(D, Env);
-} else {
-  for (auto *D : DS->getDeclGroup())
-initGlobalVar(*D, Env);
-}
-  } else if (auto *E = dyn_cast(&S)) {
-initGlobalVar(*E->getDecl(), Env);
-  } else if (auto *E = dyn_cast(&S)) {
-initGlobalVar(*E->getMemberDecl(), Env);
-  }
-}
-
 Environment::Environment(DataflowAnalysisContext &DACtx,
  const DeclContext &DeclCtx)
 : Environment(DACtx) {
   if (const auto *FuncDecl = dyn_cast(&DeclCtx)) {
-assert(FuncDecl->getBody() != nullptr);
-initGlobalVars(*FuncDecl->getBody(), *this);
 for (const auto *ParamDecl : FuncDecl->parameters()) {
   assert(ParamDecl != nullptr);
   auto &ParamLoc = createStorageLocation(*ParamDecl);

diff  --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index 4b5d23593a4bd..cd9b8b0e454e4 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -136,11 +136,6 @@ class TransferVisitor : public 
ConstStmtVisitor {
 // Group decls are converted into single decls in the CFG so the cast below
 // is safe.
 const auto &D = *cast(S->getSingleDecl());
-
-// Static local vars are already initialized in `Environment`.
-if (D.hasGlobalStorage())
-  return;
-
 auto &Loc = Env.createStorageLocation(D);
 Env.setStorageLocation(D, Loc);
 
@@ -296,24 +291,6 @@ class TransferVisitor : public 
ConstStmtVisitor {
 if (Member->isFunctionOrFunctionTemplate())
   return;
 
-if (auto *D = dyn_cast(Member)) {
-  if (D->hasGlobalStorage()) {
-auto *VarDeclLoc = Env.getStorageLocation(*D, SkipPast::None);
-if (VarDe

[PATCH] D117090: [clang-tidy] Fix `readability-non-const-parameter` for parameter referenced by an lvalue

2022-02-23 Thread gehry via Phabricator via cfe-commits
Sockke updated this revision to Diff 410753.
Sockke added a comment.

Add a release note and improve test description information.


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

https://reviews.llvm.org/D117090

Files:
  clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/readability-non-const-parameter.rst
  clang-tools-extra/test/clang-tidy/checkers/readability-non-const-parameter.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-non-const-parameter.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-non-const-parameter.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-non-const-parameter.cpp
@@ -287,3 +287,39 @@
 }
 char foo(char *s); // 2
 // CHECK-FIXES: {{^}}char foo(const char *s); // 2{{$}}
+
+void lvalueReference(int *p) {
+  // CHECK-MESSAGES-NOT: warning: pointer parameter 'p' can be
+  int &x = *p;
+}
+
+// CHECK-MESSAGES: :[[@LINE+1]]:32: warning: pointer parameter 'p' can be
+void constLValueReference(int *p) {
+  // CHECK-FIXES: {{^}}void constLValueReference(const int *p) {{{$}}
+  const int &x = *p;
+}
+
+void lambdaLVRef(int *p) {
+  // CHECK-MESSAGES-NOT: warning: pointer parameter 'p' can be
+  auto foo = [&]() {
+int &x = *p;
+  };
+}
+
+// CHECK-MESSAGES: :[[@LINE+1]]:28: warning: pointer parameter 'p' can be
+void lambdaConstLVRef(int *p) {
+  // CHECK-FIXES: {{^}}void lambdaConstLVRef(const int *p) {{{$}}
+  auto foo = [&]() {
+const int &x = *p;
+  };
+}
+
+struct Temp1 {
+  Temp1(int &i) {
+i = 10;
+  }
+};
+void constructLVRef(int *p) {
+  // CHECK-MESSAGES-NOT: warning: pointer parameter 'p' can be
+  Temp1 t(*p);
+}
Index: clang-tools-extra/docs/clang-tidy/checks/readability-non-const-parameter.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/readability-non-const-parameter.rst
+++ clang-tools-extra/docs/clang-tidy/checks/readability-non-const-parameter.rst
@@ -44,3 +44,8 @@
   int f3(struct S *p) {
 *(p->a) = 0;
   }
+
+  // no warning; p is referenced by an lvalue.
+  void f4(int *p) {
+int &x = *p;
+  }
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -158,6 +158,9 @@
   option to control whether to warn on narrowing integer to floating-point
   conversions.
 
+- Fixed a false positive in :doc:`readability-non-const-parameter
+  ` when the parameter is referenced by an lvalue
+
 
 Removed checks
 ^^
Index: clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp
@@ -83,6 +83,20 @@
   for (const auto *Arg : CE->arguments()) {
 markCanNotBeConst(Arg->IgnoreParenCasts(), true);
   }
+  // Data passed by nonconst reference should not be made const.
+  unsigned ArgNr = 0U;
+  if (const auto *CD = CE->getConstructor()) {
+for (const auto *Par : CD->parameters()) {
+  if (ArgNr >= CE->getNumArgs())
+break;
+  const Expr *Arg = CE->getArg(ArgNr++);
+  // Is this a non constant reference parameter?
+  const Type *ParType = Par->getType().getTypePtr();
+  if (!ParType->isReferenceType() || Par->getType().isConstQualified())
+continue;
+  markCanNotBeConst(Arg->IgnoreParenCasts(), false);
+}
+  }
 } else if (const auto *R = dyn_cast(S)) {
   markCanNotBeConst(R->getRetValue(), true);
 } else if (const auto *U = dyn_cast(S)) {
@@ -93,6 +107,9 @@
 if ((T->isPointerType() && !T->getPointeeType().isConstQualified()) ||
 T->isArrayType())
   markCanNotBeConst(VD->getInit(), true);
+else if (T->isLValueReferenceType() &&
+ !T->getPointeeType().isConstQualified())
+  markCanNotBeConst(VD->getInit(), false);
   }
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] e0f1dd0 - [C++20][Modules] Rework testcase to use split file [NFC].

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

Author: iains
Date: 2022-02-23T11:07:36Z
New Revision: e0f1dd018e0f94a7d694bc615975c3a7d26d9e50

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

LOG: [C++20][Modules] Rework testcase to use split file [NFC].

This switches the testcase committed for initial C++20 modules import tracking 
to
use split-file rather than preprocessor directives.

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

Added: 


Modified: 
clang/test/Modules/cxx20-import-diagnostics-a.cpp

Removed: 




diff  --git a/clang/test/Modules/cxx20-import-diagnostics-a.cpp 
b/clang/test/Modules/cxx20-import-diagnostics-a.cpp
index fd4085bcb4713..8e2940a432e6d 100644
--- a/clang/test/Modules/cxx20-import-diagnostics-a.cpp
+++ b/clang/test/Modules/cxx20-import-diagnostics-a.cpp
@@ -1,42 +1,43 @@
 // RUN: rm -rf %t
 // RUN: mkdir -p %t
+// RUN: split-file %s %t
 
-// RUN: %clang_cc1 -std=c++20 -emit-module-interface -D TU=0 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/import-diags-tu1.cpp \
 // RUN:  -o %t/B.pcm
 
-// RUN: %clang_cc1 -std=c++20 -emit-module-interface -D TU=1 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/import-diags-tu2.cpp \
 // RUN:  -o %t/C.pcm
 
-// RUN: %clang_cc1 -std=c++20 -emit-module-interface -D TU=2 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/import-diags-tu3.cpp \
 // RUN:  -fmodule-file=%t/B.pcm -fmodule-file=%t/C.pcm -o %t/AOK1.pcm
 
-// RUN: %clang_cc1 -std=c++20 -S -D TU=3 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -S %t/import-diags-tu4.cpp \
 // RUN:  -fmodule-file=%t/AOK1.pcm -o %t/tu_3.s -verify
 
-// RUN: %clang_cc1 -std=c++20 -emit-module-interface -D TU=4 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/import-diags-tu5.cpp \
 // RUN:  -fmodule-file=%t/B.pcm -fmodule-file=%t/C.pcm -o %t/BC.pcm -verify
 
-// RUN: %clang_cc1 -std=c++20 -S -D TU=5 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -S %t/import-diags-tu6.cpp \
 // RUN:  -fmodule-file=%t/B.pcm -fmodule-file=%t/C.pcm -o %t/tu_5.s -verify
 
-// RUN: %clang_cc1 -std=c++20 -emit-module-interface -D TU=6 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/import-diags-tu7.cpp \
 // RUN:  -fmodule-file=%t/B.pcm -o %t/D.pcm -verify
 
-// RUN: %clang_cc1 -std=c++20 -emit-module-interface -D TU=7 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/import-diags-tu8.cpp \
 // RUN:  -fmodule-file=%t/B.pcm -o %t/D.pcm -verify
 
-// RUN: %clang_cc1 -std=c++20 -S -D TU=8 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -S %t/import-diags-tu9.cpp \
 // RUN:  -fmodule-file=%t/B.pcm -o %t/tu_8.s -verify
 
-// RUN: %clang_cc1 -std=c++20 -emit-module-interface -D TU=9 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/import-diags-tu10.cpp \
 // RUN:  -o %t/B.pcm -verify
 
-// RUN: %clang_cc1 -std=c++20 -emit-obj -D TU=10 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-obj %t/import-diags-tu11.cpp \
 // RUN:  -fmodule-file=%t/C.pcm  -o %t/impl.o
 
 // Test diagnostics for incorrect module import sequences.
 
-#if TU == 0
+//--- import-diags-tu1.cpp
 
 export module B;
 
@@ -44,7 +45,7 @@ int foo ();
 
 // expected-no-diagnostics
 
-#elif TU == 1
+//--- import-diags-tu2.cpp
 
 export module C;
 
@@ -52,7 +53,7 @@ int bar ();
 
 // expected-no-diagnostics
 
-#elif TU == 2
+//--- import-diags-tu3.cpp
 
 export module AOK1;
 
@@ -63,7 +64,7 @@ export int theAnswer ();
 
 // expected-no-diagnostics
 
-#elif TU == 3
+//--- import-diags-tu4.cpp
 
 module;
 
@@ -73,7 +74,7 @@ export import C; // expected-error {{export declaration can 
only be used within
 
 int theAnswer () { return 42; }
 
-#elif TU == 4
+//--- import-diags-tu5.cpp
 
 export module BC;
 
@@ -83,7 +84,7 @@ int foo () { return 10; }
 
 import C; // expected-error {{imports must immediately follow the module 
declaration}}
 
-#elif TU == 5
+//--- import-diags-tu6.cpp
 
 module B; // implicitly imports B.
 
@@ -91,7 +92,7 @@ int foo () { return 10; }
 
 import C; // expected-error {{imports must immediately follow the module 
declaration}}
 
-#elif TU == 6
+//--- import-diags-tu7.cpp
 
 module;
 // We can only have preprocessor commands here, which could include an include
@@ -103,7 +104,7 @@ export module D;
 
 int delta ();
 
-#elif TU == 7
+//--- import-diags-tu8.cpp
 
 export module D;
 
@@ -113,19 +114,19 @@ module :private;
 
 import B; // expected-error {{module imports cannot be in the private module 
fragment}}
 
-#elif TU == 8
+//--- import-diags-tu9.cpp
 
 module B;
 
 import B; // expected-error {{import of module 'B' appears within same 
top-level module 'B'}}
 
-#elif TU == 9
+//--- import-diags-tu10.cpp
 
 export module B;
 
 import B; // expected-error {{import of module 'B' appears within same 
top-level module 'B'}}
 
-#el

[PATCH] D120352: [C++20][Modules] Rework testcase to use split file [NFC].

2022-02-23 Thread Iain Sandoe 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 rGe0f1dd018e0f: [C++20][Modules] Rework testcase to use split 
file [NFC]. (authored by iains).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120352

Files:
  clang/test/Modules/cxx20-import-diagnostics-a.cpp

Index: clang/test/Modules/cxx20-import-diagnostics-a.cpp
===
--- clang/test/Modules/cxx20-import-diagnostics-a.cpp
+++ clang/test/Modules/cxx20-import-diagnostics-a.cpp
@@ -1,42 +1,43 @@
 // RUN: rm -rf %t
 // RUN: mkdir -p %t
+// RUN: split-file %s %t
 
-// RUN: %clang_cc1 -std=c++20 -emit-module-interface -D TU=0 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/import-diags-tu1.cpp \
 // RUN:  -o %t/B.pcm
 
-// RUN: %clang_cc1 -std=c++20 -emit-module-interface -D TU=1 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/import-diags-tu2.cpp \
 // RUN:  -o %t/C.pcm
 
-// RUN: %clang_cc1 -std=c++20 -emit-module-interface -D TU=2 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/import-diags-tu3.cpp \
 // RUN:  -fmodule-file=%t/B.pcm -fmodule-file=%t/C.pcm -o %t/AOK1.pcm
 
-// RUN: %clang_cc1 -std=c++20 -S -D TU=3 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -S %t/import-diags-tu4.cpp \
 // RUN:  -fmodule-file=%t/AOK1.pcm -o %t/tu_3.s -verify
 
-// RUN: %clang_cc1 -std=c++20 -emit-module-interface -D TU=4 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/import-diags-tu5.cpp \
 // RUN:  -fmodule-file=%t/B.pcm -fmodule-file=%t/C.pcm -o %t/BC.pcm -verify
 
-// RUN: %clang_cc1 -std=c++20 -S -D TU=5 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -S %t/import-diags-tu6.cpp \
 // RUN:  -fmodule-file=%t/B.pcm -fmodule-file=%t/C.pcm -o %t/tu_5.s -verify
 
-// RUN: %clang_cc1 -std=c++20 -emit-module-interface -D TU=6 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/import-diags-tu7.cpp \
 // RUN:  -fmodule-file=%t/B.pcm -o %t/D.pcm -verify
 
-// RUN: %clang_cc1 -std=c++20 -emit-module-interface -D TU=7 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/import-diags-tu8.cpp \
 // RUN:  -fmodule-file=%t/B.pcm -o %t/D.pcm -verify
 
-// RUN: %clang_cc1 -std=c++20 -S -D TU=8 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -S %t/import-diags-tu9.cpp \
 // RUN:  -fmodule-file=%t/B.pcm -o %t/tu_8.s -verify
 
-// RUN: %clang_cc1 -std=c++20 -emit-module-interface -D TU=9 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/import-diags-tu10.cpp \
 // RUN:  -o %t/B.pcm -verify
 
-// RUN: %clang_cc1 -std=c++20 -emit-obj -D TU=10 -x c++ %s \
+// RUN: %clang_cc1 -std=c++20 -emit-obj %t/import-diags-tu11.cpp \
 // RUN:  -fmodule-file=%t/C.pcm  -o %t/impl.o
 
 // Test diagnostics for incorrect module import sequences.
 
-#if TU == 0
+//--- import-diags-tu1.cpp
 
 export module B;
 
@@ -44,7 +45,7 @@
 
 // expected-no-diagnostics
 
-#elif TU == 1
+//--- import-diags-tu2.cpp
 
 export module C;
 
@@ -52,7 +53,7 @@
 
 // expected-no-diagnostics
 
-#elif TU == 2
+//--- import-diags-tu3.cpp
 
 export module AOK1;
 
@@ -63,7 +64,7 @@
 
 // expected-no-diagnostics
 
-#elif TU == 3
+//--- import-diags-tu4.cpp
 
 module;
 
@@ -73,7 +74,7 @@
 
 int theAnswer () { return 42; }
 
-#elif TU == 4
+//--- import-diags-tu5.cpp
 
 export module BC;
 
@@ -83,7 +84,7 @@
 
 import C; // expected-error {{imports must immediately follow the module declaration}}
 
-#elif TU == 5
+//--- import-diags-tu6.cpp
 
 module B; // implicitly imports B.
 
@@ -91,7 +92,7 @@
 
 import C; // expected-error {{imports must immediately follow the module declaration}}
 
-#elif TU == 6
+//--- import-diags-tu7.cpp
 
 module;
 // We can only have preprocessor commands here, which could include an include
@@ -103,7 +104,7 @@
 
 int delta ();
 
-#elif TU == 7
+//--- import-diags-tu8.cpp
 
 export module D;
 
@@ -113,19 +114,19 @@
 
 import B; // expected-error {{module imports cannot be in the private module fragment}}
 
-#elif TU == 8
+//--- import-diags-tu9.cpp
 
 module B;
 
 import B; // expected-error {{import of module 'B' appears within same top-level module 'B'}}
 
-#elif TU == 9
+//--- import-diags-tu10.cpp
 
 export module B;
 
 import B; // expected-error {{import of module 'B' appears within same top-level module 'B'}}
 
-#elif TU == 10
+//--- import-diags-tu11.cpp
 
 int x;
 
@@ -134,7 +135,3 @@
 int baz() { return 6174; }
 
 // expected-no-diagnostics
-
-#else
-#error "no MODE set"
-#endif
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] fbe38a7 - [NFC][Lexer] Make access to LangOpts more consistent

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

Author: Dawid Jurczak
Date: 2022-02-23T12:46:13+01:00
New Revision: fbe38a784e2852b22f5a44ad417e071ff583d57d

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

LOG: [NFC][Lexer] Make access to LangOpts more consistent

Before this change without any good reason Lexer::LangOpts is sometimes 
accessed by getter and another time read directly in Lexer functions.
Since getLangOpts is a bit more verbose prefer direct access to LangOpts member 
when possible.

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

Added: 


Modified: 
clang/lib/Lex/Lexer.cpp

Removed: 




diff  --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp
index a180bba365cf..4f8910e7ac9e 100644
--- a/clang/lib/Lex/Lexer.cpp
+++ b/clang/lib/Lex/Lexer.cpp
@@ -1881,7 +1881,7 @@ bool Lexer::LexNumericConstant(Token &Result, const char 
*CurPtr) {
 if (!LangOpts.C99) {
   if (!isHexaLiteral(BufferPtr, LangOpts))
 IsHexFloat = false;
-  else if (!getLangOpts().CPlusPlus17 &&
+  else if (!LangOpts.CPlusPlus17 &&
std::find(BufferPtr, CurPtr, '_') != CurPtr)
 IsHexFloat = false;
 }
@@ -1890,12 +1890,12 @@ bool Lexer::LexNumericConstant(Token &Result, const 
char *CurPtr) {
   }
 
   // If we have a digit separator, continue.
-  if (C == '\'' && (getLangOpts().CPlusPlus14 || getLangOpts().C2x)) {
+  if (C == '\'' && (LangOpts.CPlusPlus14 || LangOpts.C2x)) {
 unsigned NextSize;
-char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
+char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, LangOpts);
 if (isAsciiIdentifierContinue(Next)) {
   if (!isLexingRawMode())
-Diag(CurPtr, getLangOpts().CPlusPlus
+Diag(CurPtr, LangOpts.CPlusPlus
  ? diag::warn_cxx11_compat_digit_separator
  : diag::warn_c2x_compat_digit_separator);
   CurPtr = ConsumeChar(CurPtr, Size, Result);
@@ -1921,7 +1921,7 @@ bool Lexer::LexNumericConstant(Token &Result, const char 
*CurPtr) {
 /// in C++11, or warn on a ud-suffix in C++98.
 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
bool IsStringLiteral) {
-  assert(getLangOpts().CPlusPlus);
+  assert(LangOpts.CPlusPlus);
 
   // Maximally munch an identifier.
   unsigned Size;
@@ -1937,7 +1937,7 @@ const char *Lexer::LexUDSuffix(Token &Result, const char 
*CurPtr,
   return CurPtr;
   }
 
-  if (!getLangOpts().CPlusPlus11) {
+  if (!LangOpts.CPlusPlus11) {
 if (!isLexingRawMode())
   Diag(CurPtr,
C == '_' ? diag::warn_cxx11_compat_user_defined_literal
@@ -1955,7 +1955,7 @@ const char *Lexer::LexUDSuffix(Token &Result, const char 
*CurPtr,
 bool IsUDSuffix = false;
 if (C == '_')
   IsUDSuffix = true;
-else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
+else if (IsStringLiteral && LangOpts.CPlusPlus14) {
   // In C++1y, we need to look ahead a few characters to see if this is a
   // valid suffix for a string literal or a numeric literal (this could be
   // the 'operator""if' defining a numeric literal operator).
@@ -1965,13 +1965,12 @@ const char *Lexer::LexUDSuffix(Token &Result, const 
char *CurPtr,
   unsigned Chars = 1;
   while (true) {
 unsigned NextSize;
-char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
- getLangOpts());
+char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize, 
LangOpts);
 if (!isAsciiIdentifierContinue(Next)) {
   // End of suffix. Check whether this is on the allowed list.
   const StringRef CompleteSuffix(Buffer, Chars);
-  IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
-CompleteSuffix);
+  IsUDSuffix =
+  StringLiteralParser::isValidUDSuffix(LangOpts, CompleteSuffix);
   break;
 }
 
@@ -1986,10 +1985,10 @@ const char *Lexer::LexUDSuffix(Token &Result, const 
char *CurPtr,
 
 if (!IsUDSuffix) {
   if (!isLexingRawMode())
-Diag(CurPtr, getLangOpts().MSVCCompat
+Diag(CurPtr, LangOpts.MSVCCompat
  ? diag::ext_ms_reserved_user_defined_literal
  : diag::ext_reserved_user_defined_literal)
-  << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
+<< FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
   return CurPtr;
 }
 
@@ -2022,9 +2021,8 @@ bool Lexer::LexStringLiteral(Token &Result, const char 
*CurPtr,
   (Kind == tok::utf8_string_literal ||
Kind == tok::utf16_string_literal ||
Kind == tok::utf32_string_literal))
-Diag(BufferPtr

[PATCH] D120333: [NFC][Lexer] Make access to LangOpts more consistent

2022-02-23 Thread Dawid Jurczak 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 rGfbe38a784e28: [NFC][Lexer] Make access to LangOpts more 
consistent (authored by yurai007).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120333

Files:
  clang/lib/Lex/Lexer.cpp

Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -1881,7 +1881,7 @@
 if (!LangOpts.C99) {
   if (!isHexaLiteral(BufferPtr, LangOpts))
 IsHexFloat = false;
-  else if (!getLangOpts().CPlusPlus17 &&
+  else if (!LangOpts.CPlusPlus17 &&
std::find(BufferPtr, CurPtr, '_') != CurPtr)
 IsHexFloat = false;
 }
@@ -1890,12 +1890,12 @@
   }
 
   // If we have a digit separator, continue.
-  if (C == '\'' && (getLangOpts().CPlusPlus14 || getLangOpts().C2x)) {
+  if (C == '\'' && (LangOpts.CPlusPlus14 || LangOpts.C2x)) {
 unsigned NextSize;
-char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
+char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, LangOpts);
 if (isAsciiIdentifierContinue(Next)) {
   if (!isLexingRawMode())
-Diag(CurPtr, getLangOpts().CPlusPlus
+Diag(CurPtr, LangOpts.CPlusPlus
  ? diag::warn_cxx11_compat_digit_separator
  : diag::warn_c2x_compat_digit_separator);
   CurPtr = ConsumeChar(CurPtr, Size, Result);
@@ -1921,7 +1921,7 @@
 /// in C++11, or warn on a ud-suffix in C++98.
 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
bool IsStringLiteral) {
-  assert(getLangOpts().CPlusPlus);
+  assert(LangOpts.CPlusPlus);
 
   // Maximally munch an identifier.
   unsigned Size;
@@ -1937,7 +1937,7 @@
   return CurPtr;
   }
 
-  if (!getLangOpts().CPlusPlus11) {
+  if (!LangOpts.CPlusPlus11) {
 if (!isLexingRawMode())
   Diag(CurPtr,
C == '_' ? diag::warn_cxx11_compat_user_defined_literal
@@ -1955,7 +1955,7 @@
 bool IsUDSuffix = false;
 if (C == '_')
   IsUDSuffix = true;
-else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
+else if (IsStringLiteral && LangOpts.CPlusPlus14) {
   // In C++1y, we need to look ahead a few characters to see if this is a
   // valid suffix for a string literal or a numeric literal (this could be
   // the 'operator""if' defining a numeric literal operator).
@@ -1965,13 +1965,12 @@
   unsigned Chars = 1;
   while (true) {
 unsigned NextSize;
-char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
- getLangOpts());
+char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize, LangOpts);
 if (!isAsciiIdentifierContinue(Next)) {
   // End of suffix. Check whether this is on the allowed list.
   const StringRef CompleteSuffix(Buffer, Chars);
-  IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
-CompleteSuffix);
+  IsUDSuffix =
+  StringLiteralParser::isValidUDSuffix(LangOpts, CompleteSuffix);
   break;
 }
 
@@ -1986,10 +1985,10 @@
 
 if (!IsUDSuffix) {
   if (!isLexingRawMode())
-Diag(CurPtr, getLangOpts().MSVCCompat
+Diag(CurPtr, LangOpts.MSVCCompat
  ? diag::ext_ms_reserved_user_defined_literal
  : diag::ext_reserved_user_defined_literal)
-  << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
+<< FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
   return CurPtr;
 }
 
@@ -2022,9 +2021,8 @@
   (Kind == tok::utf8_string_literal ||
Kind == tok::utf16_string_literal ||
Kind == tok::utf32_string_literal))
-Diag(BufferPtr, getLangOpts().CPlusPlus
-   ? diag::warn_cxx98_compat_unicode_literal
-   : diag::warn_c99_compat_unicode_literal);
+Diag(BufferPtr, LangOpts.CPlusPlus ? diag::warn_cxx98_compat_unicode_literal
+   : diag::warn_c99_compat_unicode_literal);
 
   char C = getAndAdvanceChar(CurPtr, Result);
   while (C != '"') {
@@ -2058,7 +2056,7 @@
   }
 
   // If we are in C++11, lex the optional ud-suffix.
-  if (getLangOpts().CPlusPlus)
+  if (LangOpts.CPlusPlus)
 CurPtr = LexUDSuffix(Result, CurPtr, true);
 
   // If a nul character existed in the string, warn about it.
@@ -2142,7 +2140,7 @@
   }
 
   // If we are in C++11, lex the optional ud-suffix.
-  if (getLangOpts().CPlusPlus)
+  if (LangOpts.CPlusPlus)
 CurPtr = LexUDSuffix(Result, CurPtr, true);
 
   // Update the location of token as well as BufferPtr.
@@ -2238,7 +2236,7 @@
 
   if (!isLexingRawMode()) {
 if (Kind 

[PATCH] D120310: [clang][analyzer] Add modeling of 'errno' (work-in-progress).

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



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h:767-768
s->getType()->isBlockPointerType());
-assert(isa(sreg) || isa(sreg));
+assert(isa(sreg) || isa(sreg) ||
+   isa(sreg));
   }

NoQ wrote:
> steakhal wrote:
> > At this point, I'm not even sure if we should assert any of these.
> I mean, ideally this should be just `UnknownSpaceRegion`. For everything else 
> we should have made a fresh `MemRegion` class. It is absurd that the same 
> numeric address value (represented the symbol `s`) can correspond to two (now 
> three) different locations in memory.
From my perspective, a symbolic region is just a region that we don't know what 
its parent region is - let it be part of an object or an entire memory space.
The memory space is what we use for communicating some constraints on where 
that symbolic region.
E.g. a symbolic region of a stack memory space should never alias with any 
memory region of the heap memory space.

> It is absurd that the same numeric address value (represented the symbol s) 
> can correspond to two (now three) different locations in memory.
IMO a given `s` should indeed refer to a single location in memory, but that's 
not a property we can enforce here in the constructor.
And my guess is that by removing this assertion, we would still have this 
invariant. What we should do instead, put an assertion into the 
`SymbolManager`, to enforce that with the same `s` symbol, one cannot construct 
two `SymbolicRegions` with different memory spaces.
Alternatively, we could remove the memory space from the `Profile` to map to 
the same entity in the Map; which would enforce this invariant on its own. WDYT?



Comment at: clang/lib/StaticAnalyzer/Checkers/Errno.h:24-26
+/// Returns if modeling of 'errno' is available.
+/// If not, the other functions here should not be used.
+bool isErrnoAvailable(ProgramStateRef State);

NoQ wrote:
> steakhal wrote:
> > I don't think we need this.
> > In `getErrnoValue()` we should simply return `UnknownVal` if we don't have 
> > 'errno.
> > And in `setErrnoValue()` we should return the incoming `State` unmodified.
> > 
> > THat being said, only a top-level `Check::BeginFunction` callback could see 
> > an 'errno' uninitialized, which I don't think is a real issue.
> > All the rest of the callbacks would run after it's initialized, thus would 
> > behave as expected.
> > And in case the translation unit doesn't have nor 'errno' variable nor 
> > 'errno_location_ish' functions, ignoring these `set/get` functions is 
> > actually the expected behavior.
> > 
> > Having to check `isErrnoAvailable()` would be really an anti-pattern.
> `UnknownVal` implies that it's an actual value but we don't know which one. 
> If the value doesn't exist we shouldn't use it. And if the user doesn't 
> include the appropriate header then the value really doesn't exist in the 
> translation unit. So flavor-wise I think we shouldn't use `UnknownVal` here; 
> I'd rather have an `Optional`.
> 
> Other than that, yeah, I think this is a good suggestion.
Yeah, probably the `Optional` is a better alternative.

However, I'd like to explain my reasoning behind my previous suggestion:
`Unknown` can/should model any values that the analyzer cannot currently reason 
about: e.g. floating-point numbers.
In this case, we cannot reason about the `errno`, thus I recommended it.

My point is, that we shouldn't regress our API for a marginal problem. And 
according to my reasoning, this seems to be a marginal issue.
Using `Optional` here is better than the current implementation, but not by 
much.
It would still result in a suboptimal coding pattern, where we guard each 
access to get/set `errno` by an `if` statement. In the cases where we would use 
the `getOr()` getter, I'm expecting to see the users pass the `UnknownVal()` as 
the fallback value in most cases anyway.



Comment at: clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp:32
+// FIXME: Is there a system where it is not called "errno" but is a variable?
+const char *ErrnoVarName = "errno";
+// Names of functions that return a location of the "errno" value.

NoQ wrote:
> steakhal wrote:
> > Why don't you use `StringRef` here as well?
> There's [[ 
> https://llvm.org/docs/CodingStandards.html#do-not-use-static-constructors | 
> that rule against static constructors/destructors ]]. We should use a lot of 
> `constexpr` in these situations and/or try to turn these structures into 
> plain C arrays as much as possible.
Ah, I see, thanks!



Comment at: clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp:134
+const SymbolConjured *Sym =
+SVB.conjureSymbol(nullptr, C.getLocationContext(), ACtx.IntTy, 1);
+

NoQ wrote:
> steakhal wrote:
> > 
> This is literally the first step of the analysis. The block count is 
> /

[PATCH] D120401: [clang-format][NFC] Rename test and remove comments

2022-02-23 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks created this revision.
HazardyKnusperkeks added reviewers: owenpan, MyDeveloperDay, curdeius.
HazardyKnusperkeks added a project: clang-format.
HazardyKnusperkeks requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Why put "InMacros" in the name? We test other things to, and I will add more, 
withut macros.

Also all our tests are regression tests.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120401

Files:
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -44,9 +44,7 @@
 EXPECT_TOKEN_TYPE(FormatTok, Type);
\
   } while (false)
 
-TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmpInMacroDefinition) {
-  // This is a regression test for mis-parsing the & after decltype as a binary
-  // operator instead of a reference (when inside a macro definition).
+TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) {
   auto Tokens = annotate("auto x = [](const decltype(x) &ptr) {};");
   EXPECT_EQ(Tokens.size(), 18u) << Tokens;
   EXPECT_TOKEN(Tokens[7], tok::kw_decltype, TT_Unknown);
@@ -54,13 +52,12 @@
   EXPECT_TOKEN(Tokens[9], tok::identifier, TT_Unknown);
   EXPECT_TOKEN(Tokens[10], tok::r_paren, TT_TypeDeclarationParen);
   EXPECT_TOKEN(Tokens[11], tok::amp, TT_PointerOrReference);
-  // Same again with * instead of &:
+
   Tokens = annotate("auto x = [](const decltype(x) *ptr) {};");
   EXPECT_EQ(Tokens.size(), 18u) << Tokens;
   EXPECT_TOKEN(Tokens[10], tok::r_paren, TT_TypeDeclarationParen);
   EXPECT_TOKEN(Tokens[11], tok::star, TT_PointerOrReference);
 
-  // Also check that we parse correctly within a macro definition:
   Tokens = annotate("#define lambda [](const decltype(x) &ptr) {}");
   EXPECT_EQ(Tokens.size(), 17u) << Tokens;
   EXPECT_TOKEN(Tokens[7], tok::kw_decltype, TT_Unknown);
@@ -68,7 +65,7 @@
   EXPECT_TOKEN(Tokens[9], tok::identifier, TT_Unknown);
   EXPECT_TOKEN(Tokens[10], tok::r_paren, TT_TypeDeclarationParen);
   EXPECT_TOKEN(Tokens[11], tok::amp, TT_PointerOrReference);
-  // Same again with * instead of &:
+
   Tokens = annotate("#define lambda [](const decltype(x) *ptr) {}");
   EXPECT_EQ(Tokens.size(), 17u) << Tokens;
   EXPECT_TOKEN(Tokens[10], tok::r_paren, TT_TypeDeclarationParen);


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -44,9 +44,7 @@
 EXPECT_TOKEN_TYPE(FormatTok, Type);\
   } while (false)
 
-TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmpInMacroDefinition) {
-  // This is a regression test for mis-parsing the & after decltype as a binary
-  // operator instead of a reference (when inside a macro definition).
+TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) {
   auto Tokens = annotate("auto x = [](const decltype(x) &ptr) {};");
   EXPECT_EQ(Tokens.size(), 18u) << Tokens;
   EXPECT_TOKEN(Tokens[7], tok::kw_decltype, TT_Unknown);
@@ -54,13 +52,12 @@
   EXPECT_TOKEN(Tokens[9], tok::identifier, TT_Unknown);
   EXPECT_TOKEN(Tokens[10], tok::r_paren, TT_TypeDeclarationParen);
   EXPECT_TOKEN(Tokens[11], tok::amp, TT_PointerOrReference);
-  // Same again with * instead of &:
+
   Tokens = annotate("auto x = [](const decltype(x) *ptr) {};");
   EXPECT_EQ(Tokens.size(), 18u) << Tokens;
   EXPECT_TOKEN(Tokens[10], tok::r_paren, TT_TypeDeclarationParen);
   EXPECT_TOKEN(Tokens[11], tok::star, TT_PointerOrReference);
 
-  // Also check that we parse correctly within a macro definition:
   Tokens = annotate("#define lambda [](const decltype(x) &ptr) {}");
   EXPECT_EQ(Tokens.size(), 17u) << Tokens;
   EXPECT_TOKEN(Tokens[7], tok::kw_decltype, TT_Unknown);
@@ -68,7 +65,7 @@
   EXPECT_TOKEN(Tokens[9], tok::identifier, TT_Unknown);
   EXPECT_TOKEN(Tokens[10], tok::r_paren, TT_TypeDeclarationParen);
   EXPECT_TOKEN(Tokens[11], tok::amp, TT_PointerOrReference);
-  // Same again with * instead of &:
+
   Tokens = annotate("#define lambda [](const decltype(x) *ptr) {}");
   EXPECT_EQ(Tokens.size(), 17u) << Tokens;
   EXPECT_TOKEN(Tokens[10], tok::r_paren, TT_TypeDeclarationParen);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a848a5c - Revert "Revert "[analyzer] Fix taint propagation by remembering to the location context""

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

Author: Balazs Benics
Date: 2022-02-23T12:53:07+01:00
New Revision: a848a5cf2f2f2f8a621bdc5a12e0fe49dc743176

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

LOG: Revert "Revert "[analyzer] Fix taint propagation by remembering to the 
location context""

This reverts commit d16c5f4192c30d53468a472c6820163a81192825.

Let's try `REQUIRES: asserts`.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
clang/test/Analysis/taint-checker-callback-order-has-definition.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
index 428778e6cfaa..66143f78932c 100644
--- a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
@@ -38,6 +38,8 @@ using namespace clang;
 using namespace ento;
 using namespace taint;
 
+using llvm::ImmutableSet;
+
 namespace {
 
 class GenericTaintChecker;
@@ -434,7 +436,9 @@ template <> struct 
ScalarEnumerationTraits {
 /// to the call post-visit. The values are signed integers, which are either
 /// ReturnValueIndex, or indexes of the pointer/reference argument, which
 /// points to data, which should be tainted on return.
-REGISTER_SET_WITH_PROGRAMSTATE(TaintArgsOnPostVisit, ArgIdxTy)
+REGISTER_MAP_WITH_PROGRAMSTATE(TaintArgsOnPostVisit, const LocationContext *,
+   ImmutableSet)
+REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(ArgIdxFactory, ArgIdxTy)
 
 void GenericTaintRuleParser::validateArgVector(const std::string &Option,
const ArgVecTy &Args) const {
@@ -685,22 +689,26 @@ void GenericTaintChecker::checkPostCall(const CallEvent 
&Call,
   // Set the marked values as tainted. The return value only accessible from
   // checkPostStmt.
   ProgramStateRef State = C.getState();
+  const StackFrameContext *CurrentFrame = C.getStackFrame();
 
   // Depending on what was tainted at pre-visit, we determined a set of
   // arguments which should be tainted after the function returns. These are
   // stored in the state as TaintArgsOnPostVisit set.
-  TaintArgsOnPostVisitTy TaintArgs = State->get();
-  if (TaintArgs.isEmpty())
+  TaintArgsOnPostVisitTy TaintArgsMap = State->get();
+
+  const ImmutableSet *TaintArgs = TaintArgsMap.lookup(CurrentFrame);
+  if (!TaintArgs)
 return;
+  assert(!TaintArgs->isEmpty());
 
   LLVM_DEBUG(for (ArgIdxTy I
-  : TaintArgs) {
+  : *TaintArgs) {
 llvm::dbgs() << "PostCall<";
 Call.dump(llvm::dbgs());
 llvm::dbgs() << "> actually wants to taint arg index: " << I << '\n';
   });
 
-  for (ArgIdxTy ArgNum : TaintArgs) {
+  for (ArgIdxTy ArgNum : *TaintArgs) {
 // Special handling for the tainted return value.
 if (ArgNum == ReturnValueIndex) {
   State = addTaint(State, Call.getReturnValue());
@@ -714,7 +722,7 @@ void GenericTaintChecker::checkPostCall(const CallEvent 
&Call,
   }
 
   // Clear up the taint info from the state.
-  State = State->remove();
+  State = State->remove(CurrentFrame);
   C.addTransition(State);
 }
 
@@ -776,28 +784,33 @@ void GenericTaintRule::process(const GenericTaintChecker 
&Checker,
   };
 
   /// Propagate taint where it is necessary.
+  auto &F = State->getStateManager().get_context();
+  ImmutableSet Result = F.getEmptySet();
   ForEachCallArg(
-  [this, &State, WouldEscape, &Call](ArgIdxTy I, const Expr *E, SVal V) {
+  [this, WouldEscape, &Call, &Result, &F](ArgIdxTy I, const Expr *E,
+  SVal V) {
 if (PropDstArgs.contains(I)) {
   LLVM_DEBUG(llvm::dbgs() << "PreCall<"; Call.dump(llvm::dbgs());
  llvm::dbgs()
  << "> prepares tainting arg index: " << I << '\n';);
-  State = State->add(I);
+  Result = F.add(Result, I);
 }
 
 // TODO: We should traverse all reachable memory regions via the
 // escaping parameter. Instead of doing that we simply mark only the
 // referred memory region as tainted.
 if (WouldEscape(V, E->getType())) {
-  LLVM_DEBUG(if (!State->contains(I)) {
+  LLVM_DEBUG(if (!Result.contains(I)) {
 llvm::dbgs() << "PreCall<";
 Call.dump(llvm::dbgs());
 llvm::dbgs() << "> prepares tainting arg index: " << I << '\n';
   });
-  State = State->add(I);
+  Result = F.add(Result, I);
 }
   });
 
+  if (!Result.isEmpty())
+State = State->set(C.getStackFrame(), Result);
   C.addTransition(State);
 }
 
@@ -888,7 +901,11 @@ void GenericTaintChecker::taintUnsafeSocketProtocol(const 
CallEvent &Call,
   if (SafeProtocol)
 r

[clang] 7036413 - Revert "Revert "[analyzer] Fix taint rule of fgets and setproctitle_init""

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

Author: Balazs Benics
Date: 2022-02-23T12:55:31+01:00
New Revision: 7036413dc21254c8bf2f4ac62a3b087bc4b94ce8

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

LOG: Revert "Revert "[analyzer] Fix taint rule of fgets and setproctitle_init""

This reverts commit 2acead35c1289d2b3593a992b0639ca6427e481f.

Let's try `REQUIRES: asserts`.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
clang/test/Analysis/taint-checker-callback-order-has-definition.c
clang/test/Analysis/taint-checker-callback-order-without-definition.c
clang/test/Analysis/taint-generic.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
index 66143f78932c..d15a4659a96e 100644
--- a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
@@ -559,7 +559,7 @@ void GenericTaintChecker::initTaintRules(CheckerContext &C) 
const {
   {{"atoll"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
   {{"fgetc"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
   {{"fgetln"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
-  {{"fgets"}, TR::Prop({{2}}, {{0}, ReturnValueIndex})},
+  {{"fgets"}, TR::Prop({{2}}, {{0, ReturnValueIndex}})},
   {{"fscanf"}, TR::Prop({{0}}, {{}, 2})},
   {{"sscanf"}, TR::Prop({{0}}, {{}, 2})},
   {{"getc"}, TR::Prop({{0}}, {{ReturnValueIndex}})},
@@ -632,7 +632,7 @@ void GenericTaintChecker::initTaintRules(CheckerContext &C) 
const {
   if (TR::UntrustedEnv(C)) {
 // void setproctitle_init(int argc, char *argv[], char *envp[])
 GlobalCRules.push_back(
-{{{"setproctitle_init"}}, TR::Sink({{2}}, MsgCustomSink)});
+{{{"setproctitle_init"}}, TR::Sink({{1, 2}}, MsgCustomSink)});
 GlobalCRules.push_back({{"getenv"}, TR::Source({{ReturnValueIndex}})});
   }
 

diff  --git a/clang/test/Analysis/taint-checker-callback-order-has-definition.c 
b/clang/test/Analysis/taint-checker-callback-order-has-definition.c
index f718fa5a49fc..eaf96cc675f0 100644
--- a/clang/test/Analysis/taint-checker-callback-order-has-definition.c
+++ b/clang/test/Analysis/taint-checker-callback-order-has-definition.c
@@ -27,11 +27,9 @@ void top(const char *fname, char *buf) {
   (void)fgets(buf, 42, fp); // Trigger taint propagation.
   // CHECK-NEXT: PreCall prepares tainting arg index: -1
   // CHECK-NEXT: PreCall prepares tainting arg index: 0
-  // CHECK-NEXT: PreCall prepares tainting arg index: 1
   // CHECK-NEXT: PreCall prepares tainting arg index: 2
-
+  //
   // CHECK-NEXT: PostCall actually wants to taint arg 
index: -1
   // CHECK-NEXT: PostCall actually wants to taint arg 
index: 0
-  // CHECK-NEXT: PostCall actually wants to taint arg 
index: 1
   // CHECK-NEXT: PostCall actually wants to taint arg 
index: 2
 }

diff  --git 
a/clang/test/Analysis/taint-checker-callback-order-without-definition.c 
b/clang/test/Analysis/taint-checker-callback-order-without-definition.c
index dba23f367fd6..6de87f736926 100644
--- a/clang/test/Analysis/taint-checker-callback-order-without-definition.c
+++ b/clang/test/Analysis/taint-checker-callback-order-without-definition.c
@@ -21,16 +21,11 @@ void top(const char *fname, char *buf) {
 
   (void)fgets(buf, 42, fp); // Trigger taint propagation.
 
-  // FIXME: Why is the arg index 1 prepared for taint?
-  // Before the call it wasn't tainted, and it also shouldn't be tainted after 
the call.
-
   // CHECK-NEXT: PreCall prepares tainting arg index: -1
   // CHECK-NEXT: PreCall prepares tainting arg index: 0
-  // CHECK-NEXT: PreCall prepares tainting arg index: 1
   // CHECK-NEXT: PreCall prepares tainting arg index: 2
   //
   // CHECK-NEXT: PostCall actually wants to taint arg 
index: -1
   // CHECK-NEXT: PostCall actually wants to taint arg 
index: 0
-  // CHECK-NEXT: PostCall actually wants to taint arg 
index: 1
   // CHECK-NEXT: PostCall actually wants to taint arg 
index: 2
 }

diff  --git a/clang/test/Analysis/taint-generic.c 
b/clang/test/Analysis/taint-generic.c
index 6979c0667764..0612e1b9f98b 100644
--- a/clang/test/Analysis/taint-generic.c
+++ b/clang/test/Analysis/taint-generic.c
@@ -58,9 +58,11 @@ extern FILE *stdin;
 
 #define bool _Bool
 
+char *getenv(const char *name);
 int fscanf(FILE *restrict stream, const char *restrict format, ...);
 int sprintf(char *str, const char *format, ...);
 void setproctitle(const char *fmt, ...);
+void setproctitle_init(int argc, char *argv[], char *envp[]);
 typedef __typeof(sizeof(int)) size_t;
 
 // Define string functions. Use builtin for some of them. They all default to
@@ -404,3 +406,20 @@ void testConfigurationSinks(void) {
 void testUnknownFunction(void (*foo)(void)) {
   foo(); // no-crash
 }
+
+voi

[PATCH] D119601: [analyzer] Refactor makeNull to makeNullWithWidth (NFC)

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

I'm satisfied. I cannot see any issues.
AFAI remember the tests runs uncovered no report changes - as expected from an 
NFC change.
So it's good to go on my part.
Wait for a review from @NoQ, just to be sure. Unless Artem has objections, just 
commit this and the whole patch stack next week.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119601

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


[PATCH] D118987: [analyzer] Add failing test case demonstrating buggy taint propagation

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

In D118987#3332940 , @jrtc27 wrote:

> In D118987#3319697 , @steakhal 
> wrote:
>
>> It seems like the `clang-ve-ninja` doesn't really want to accept any patches 
>> from me :D
>> I hope it's not personal. Let's be friends bot, please.
>>
>> Link to the breakage: https://lab.llvm.org/buildbot/#/builders/91/builds/3818
>>
>> I'm inviting @simoll for resolving this, and the underlying issue to prevent 
>> future breakages and reverts.
>
> As stated in 
> https://discourse.llvm.org/t/the-angry-clang-ve-ninja-build-bot/60330/4, it's 
> because the clang-ve-ninja bot does a build without assertions enabled, so 
> you need REQUIRES: asserts or to write the test in a way that avoids the need 
> for -debug-only.

It seems like it worked! Thanks again.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118987

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


[PATCH] D118987: [analyzer] Add failing test case demonstrating buggy taint propagation

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

Committed as fa0a80e017ebd58a71bdb4e4493bb022f80fe791 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118987

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


[PATCH] D119128: [analyzer] Fix taint propagation by remembering to the location context

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

Committed as a848a5cf2f2f2f8a621bdc5a12e0fe49dc743176 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119128

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


[PATCH] D119129: [analyzer] Fix taint rule of fgets and setproctitle_init

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

Committed as 7036413dc21254c8bf2f4ac62a3b087bc4b94ce8 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119129

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


[PATCH] D119063: [SemaCXX] Properly scope ArgumentPackSubstitutionIndex when expanding base types

2022-02-23 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added inline comments.



Comment at: clang/lib/Sema/SemaTemplateInstantiate.cpp:2536
 
-  TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
-  TemplateArgs,
-  Base.getSourceRange().getBegin(),
-  DeclarationName());
+BaseTypeLoc =
+SubstType(Base.getTypeSourceInfo(), TemplateArgs,

I'm not familiar with this code at all - but we've gone from having a local 
shadow BaseTypeLoc variable to reusing the BaseTypeLoc declared at line#2510 - 
is that what we actually want?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119063

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


[PATCH] D120254: [OpenCL] Align subgroup builtin guards

2022-02-23 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh marked an inline comment as done.
svenvh added inline comments.



Comment at: clang/lib/Headers/opencl-c-base.h:85
+// Internal feature macro to provide subgroup builtins.
+#define __opencl_subgroup_builtins 1
+#endif

azabaznov wrote:
> svenvh wrote:
> > I'm in doubt whether we could just reuse `__opencl_c_subgroups` for this?
> I think we couldn't. Those subgroup features/extensions are different, as 
> implementation may support the extension but not the feature. The difference 
> is in subgroup independent forward progress: for example, it's required by 
> the extension, but optional in OpenCL C 3.0 feature.
Thanks for confirming, I will keep the separate internal feature macro then.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120254

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


[PATCH] D119162: [Pseudo] Token/TokenStream, PP directive parser.

2022-02-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

Thanks!




Comment at: clang/include/clang/Tooling/Syntax/Pseudo/Token.h:81
+};
+static_assert(sizeof(Token) <= sizeof(char *) + 16, "Careful with layout!");
+llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Token &);

what's the purpose of this static_assert?



Comment at: clang/lib/Tooling/Syntax/Pseudo/Preprocess.cpp:60
+while (Tok->Kind != tok::eof) {
+  while (StartsDirective()) {
+PPStructure::Directive Directive;

hokein wrote:
> is there any special reason to use a nested while? it looks like we can 
> replace with an `if`. -- in each iteration, we get a Chunk result (either a 
> Code, or a Directive), something like below should probably work?
> 
> ```
> while (Tok->Kind != tok::eof) {
>   if (!StartsDirective()) {
>  // handle Chunk::Code case
>  continue;
>   } else {
>  // handle directive case.
>   }
> }
> ```
> 
> 
this comment and the one blew seem to be ignored.



Comment at: clang/test/Syntax/lex.test:2
+// RUN: clang-pseudo -source %S/Inputs/example.c -print-source | FileCheck %s 
-check-prefix=SOURCE --strict-whitespace
+ SOURCE: int is_debug() {
+SOURCE-NEXT: #ifndef NDEBUG

looks like the `example.c` can be moved into this file


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119162

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


[clang] aa9c2d1 - [OpenCL] Align subgroup builtin guards

2022-02-23 Thread Sven van Haastregt via cfe-commits

Author: Sven van Haastregt
Date: 2022-02-23T12:22:09Z
New Revision: aa9c2d19d9b73589d72114d6e0a4fb4ce42b922b

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

LOG: [OpenCL] Align subgroup builtin guards

Until now, subgroup builtins are available with `opencl-c.h` when at
least one of `cl_intel_subgroups`, `cl_khr_subgroups`, or
`__opencl_c_subgroups` is defined.  With `-fdeclare-opencl-builtins`,
subgroup builtins are conditionalized on `cl_khr_subgroups` only.

Align `-fdeclare-opencl-builtins` to `opencl-c.h` by introducing the
internal `__opencl_subgroup_builtins` macro.

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

Added: 


Modified: 
clang/lib/Headers/opencl-c-base.h
clang/lib/Headers/opencl-c.h
clang/lib/Sema/OpenCLBuiltins.td
clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl

Removed: 




diff  --git a/clang/lib/Headers/opencl-c-base.h 
b/clang/lib/Headers/opencl-c-base.h
index 5191c41bcd057..d0a0d5bdbf4f5 100644
--- a/clang/lib/Headers/opencl-c-base.h
+++ b/clang/lib/Headers/opencl-c-base.h
@@ -80,6 +80,11 @@
 #define __opencl_c_named_address_space_builtins 1
 #endif // !defined(__opencl_c_generic_address_space)
 
+#if defined(cl_intel_subgroups) || defined(cl_khr_subgroups) || 
defined(__opencl_c_subgroups)
+// Internal feature macro to provide subgroup builtins.
+#define __opencl_subgroup_builtins 1
+#endif
+
 // built-in scalar data types:
 
 /**

diff  --git a/clang/lib/Headers/opencl-c.h b/clang/lib/Headers/opencl-c.h
index 18c1c317e100f..172b2c192709f 100644
--- a/clang/lib/Headers/opencl-c.h
+++ b/clang/lib/Headers/opencl-c.h
@@ -16282,7 +16282,7 @@ queue_t __ovld get_default_queue(void);
 
 // OpenCL Extension v2.0 s9.17 - Sub-groups
 
-#if defined(cl_intel_subgroups) || defined(cl_khr_subgroups) || 
defined(__opencl_c_subgroups)
+#if defined(__opencl_subgroup_builtins)
 // Shared Sub Group Functions
 uint__ovld get_sub_group_size(void);
 uint__ovld get_max_sub_group_size(void);
@@ -16381,7 +16381,7 @@ double  __ovld __conv 
sub_group_scan_inclusive_min(double x);
 double  __ovld __conv sub_group_scan_inclusive_max(double x);
 #endif //cl_khr_fp64
 
-#endif //cl_khr_subgroups cl_intel_subgroups __opencl_c_subgroups
+#endif // __opencl_subgroup_builtins
 
 #if defined(cl_khr_subgroup_extended_types)
 char __ovld __conv sub_group_broadcast( char value, uint index );

diff  --git a/clang/lib/Sema/OpenCLBuiltins.td 
b/clang/lib/Sema/OpenCLBuiltins.td
index e6da5e34f7091..ff23a1c52ff38 100644
--- a/clang/lib/Sema/OpenCLBuiltins.td
+++ b/clang/lib/Sema/OpenCLBuiltins.td
@@ -83,7 +83,7 @@ def AtomicFp64TypeExt : 
TypeExtension<"cl_khr_int64_base_atomics cl_khr_int64_ex
 
 // FunctionExtension definitions.
 def FuncExtNone  : FunctionExtension<"">;
-def FuncExtKhrSubgroups  : 
FunctionExtension<"cl_khr_subgroups">;
+def FuncExtKhrSubgroups  : 
FunctionExtension<"__opencl_subgroup_builtins">;
 def FuncExtKhrSubgroupExtendedTypes  : 
FunctionExtension<"cl_khr_subgroup_extended_types">;
 def FuncExtKhrSubgroupNonUniformVote : 
FunctionExtension<"cl_khr_subgroup_non_uniform_vote">;
 def FuncExtKhrSubgroupBallot : 
FunctionExtension<"cl_khr_subgroup_ballot">;

diff  --git a/clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl 
b/clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
index d2d7fff02efaa..89a4646839acb 100644
--- a/clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ b/clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL -fdeclare-opencl-builtins -DNO_HEADER
 // RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL -fdeclare-opencl-builtins -finclude-default-header
-// RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL1.2 -fdeclare-opencl-builtins -DNO_HEADER
-// RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL1.2 -fdeclare-opencl-builtins -finclude-default-header
+// RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL1.2 -fdeclare-opencl-builtins -DNO_HEADER 
-cl-ext=-cl_intel_subgroups
+// RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL1.2 -fdeclare-opencl-builtins -finclude-default-header 
-cl-ext=-cl_intel_subgroups
 // RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL2.0 -fdeclare-opencl-builtins -DNO_HEADER
 // RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL2.0 -fdeclare-opencl-builtins -finclude-default-header
 // RUN:

[PATCH] D120254: [OpenCL] Align subgroup builtin guards

2022-02-23 Thread Sven van Haastregt via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
svenvh marked an inline comment as done.
Closed by commit rGaa9c2d19d9b7: [OpenCL] Align subgroup builtin guards 
(authored by svenvh).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120254

Files:
  clang/lib/Headers/opencl-c-base.h
  clang/lib/Headers/opencl-c.h
  clang/lib/Sema/OpenCLBuiltins.td
  clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl


Index: clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL -fdeclare-opencl-builtins -DNO_HEADER
 // RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL -fdeclare-opencl-builtins -finclude-default-header
-// RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL1.2 -fdeclare-opencl-builtins -DNO_HEADER
-// RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL1.2 -fdeclare-opencl-builtins -finclude-default-header
+// RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL1.2 -fdeclare-opencl-builtins -DNO_HEADER 
-cl-ext=-cl_intel_subgroups
+// RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL1.2 -fdeclare-opencl-builtins -finclude-default-header 
-cl-ext=-cl_intel_subgroups
 // RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL2.0 -fdeclare-opencl-builtins -DNO_HEADER
 // RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL2.0 -fdeclare-opencl-builtins -finclude-default-header
 // RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CL3.0 -fdeclare-opencl-builtins -finclude-default-header
@@ -79,6 +79,7 @@
 #define cl_khr_subgroup_non_uniform_arithmetic 1
 #define cl_khr_subgroup_clustered_reduce 1
 #define __opencl_c_read_write_images 1
+#define __opencl_subgroup_builtins 1
 #endif
 
 #if (__OPENCL_CPP_VERSION__ == 100 || __OPENCL_C_VERSION__ == 200)
Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -83,7 +83,7 @@
 
 // FunctionExtension definitions.
 def FuncExtNone  : FunctionExtension<"">;
-def FuncExtKhrSubgroups  : 
FunctionExtension<"cl_khr_subgroups">;
+def FuncExtKhrSubgroups  : 
FunctionExtension<"__opencl_subgroup_builtins">;
 def FuncExtKhrSubgroupExtendedTypes  : 
FunctionExtension<"cl_khr_subgroup_extended_types">;
 def FuncExtKhrSubgroupNonUniformVote : 
FunctionExtension<"cl_khr_subgroup_non_uniform_vote">;
 def FuncExtKhrSubgroupBallot : 
FunctionExtension<"cl_khr_subgroup_ballot">;
Index: clang/lib/Headers/opencl-c.h
===
--- clang/lib/Headers/opencl-c.h
+++ clang/lib/Headers/opencl-c.h
@@ -16282,7 +16282,7 @@
 
 // OpenCL Extension v2.0 s9.17 - Sub-groups
 
-#if defined(cl_intel_subgroups) || defined(cl_khr_subgroups) || 
defined(__opencl_c_subgroups)
+#if defined(__opencl_subgroup_builtins)
 // Shared Sub Group Functions
 uint__ovld get_sub_group_size(void);
 uint__ovld get_max_sub_group_size(void);
@@ -16381,7 +16381,7 @@
 double  __ovld __conv sub_group_scan_inclusive_max(double x);
 #endif //cl_khr_fp64
 
-#endif //cl_khr_subgroups cl_intel_subgroups __opencl_c_subgroups
+#endif // __opencl_subgroup_builtins
 
 #if defined(cl_khr_subgroup_extended_types)
 char __ovld __conv sub_group_broadcast( char value, uint index );
Index: clang/lib/Headers/opencl-c-base.h
===
--- clang/lib/Headers/opencl-c-base.h
+++ clang/lib/Headers/opencl-c-base.h
@@ -80,6 +80,11 @@
 #define __opencl_c_named_address_space_builtins 1
 #endif // !defined(__opencl_c_generic_address_space)
 
+#if defined(cl_intel_subgroups) || defined(cl_khr_subgroups) || 
defined(__opencl_c_subgroups)
+// Internal feature macro to provide subgroup builtins.
+#define __opencl_subgroup_builtins 1
+#endif
+
 // built-in scalar data types:
 
 /**


Index: clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror -fsyntax-only -cl-std=CL -fdeclare-opencl

[PATCH] D120395: [X86] Prohibit arithmatic operations on type `__bfloat16`

2022-02-23 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added a comment.

but its still OK to perform arithmetic with __m128bh ? 
https://simd.godbolt.org/z/Ef59Ws4M3


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120395

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


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

2022-02-23 Thread Dawid Jurczak via Phabricator via cfe-commits
yurai007 created this revision.
yurai007 added reviewers: serge-sans-paille, cor3ntin, jansvoboda11, ymandel, 
nikic, xbolva00.
yurai007 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120404

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

Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -1614,8 +1614,7 @@
 SmallString<32> SpellingBuffer;
 SpellingBuffer.resize(LToken.getLength() + 1);
 const char *Start = SpellingBuffer.data();
-unsigned Length =
-Lexer::getSpelling(LToken, Start, SourceMgr, L.getLangOpts());
+unsigned Length = L.getSpelling(LToken, Start, SourceMgr);
 uint64_t Value;
 if (StringRef(Start, Length).getAsInteger(0, Value)) {
   Diags.Report(Tok.getLocation(), diag::err_mmap_unknown_token);
Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -444,6 +444,11 @@
   return getSpellingSlow(Tok, TokStart, LangOpts, const_cast(Buffer));
 }
 
+unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
+const SourceManager &SourceMgr, bool *Invalid) {
+  return getSpelling(Tok, Buffer, SourceMgr, LangOpts, Invalid);
+}
+
 /// MeasureTokenLength - Relex the token at the specified location and return
 /// its length in bytes in the input file.  If the token needs cleaning (e.g.
 /// includes a trigraph or an escaped newline) then this count includes bytes
@@ -1193,11 +1198,11 @@
 /// prefixed with ??, emit a trigraph warning.  If trigraphs are enabled,
 /// return the result character.  Finally, emit a warning about trigraph use
 /// whether trigraphs are enabled or not.
-static char DecodeTrigraphChar(const char *CP, Lexer *L) {
+static char DecodeTrigraphChar(const char *CP, Lexer *L, bool Trigraphs) {
   char Res = GetTrigraphCharForLetter(*CP);
   if (!Res || !L) return Res;
 
-  if (!L->getLangOpts().Trigraphs) {
+  if (!Trigraphs) {
 if (!L->isLexingRawMode())
   L->Diag(CP-2, diag::trigraph_ignored);
 return 0;
@@ -1371,7 +1376,8 @@
   if (Ptr[0] == '?' && Ptr[1] == '?') {
 // If this is actually a legal trigraph (not something like "??x"), emit
 // a trigraph warning.  If so, and if trigraphs are enabled, return it.
-if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
+if (char C = DecodeTrigraphChar(Ptr + 2, Tok ? this : nullptr,
+LangOpts.Trigraphs)) {
   // Remember that this token needs to be cleaned.
   if (Tok) Tok->setFlag(Token::NeedsCleaning);
 
@@ -2542,8 +2548,8 @@
 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
 /// character (either \\n or \\r) is part of an escaped newline sequence.  Issue
 /// a diagnostic if so.  We know that the newline is inside of a block comment.
-static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
-  Lexer *L) {
+static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, Lexer *L,
+  bool Trigraphs) {
   assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
 
   // Position of the first trigraph in the ending sequence.
@@ -2594,7 +2600,7 @@
   if (TrigraphPos) {
 // If no trigraphs are enabled, warn that we ignored this trigraph and
 // ignore this * character.
-if (!L->getLangOpts().Trigraphs) {
+if (!Trigraphs) {
   if (!L->isLexingRawMode())
 L->Diag(TrigraphPos, diag::trigraph_ignored_block_comment);
   return false;
@@ -2724,7 +2730,8 @@
 break;
 
   if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
-if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
+if (isEndOfBlockCommentWithEscapedNewLine(CurPtr - 2, this,
+  LangOpts.Trigraphs)) {
   // We found the final */, though it had an escaped newline between the
   // * and /.  We're done!
   break;
Index: clang/include/clang/Lex/Lexer.h
===
--- clang/include/clang/Lex/Lexer.h
+++ clang/include/clang/Lex/Lexer.h
@@ -173,10 +173,6 @@
SourceLocation ExpansionLocEnd,
unsigned TokLen, Preprocessor &PP);
 
-  /// getLangOpts - Return the language features currently enabled.
-  /// NOTE: this lexer modifies features as a file is parsed!
-  const LangOptions &getLangOpts() const { return LangOpts; }
-
   /// getFileLoc - Return th

[PATCH] D120236: [analyzer] Add more sources to Taint analysis

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

Fewer nits this time.
We are converging!




Comment at: clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp:559
+  {{"gethostname"}, TR::Source({{0}})},
+  {{"getnameinfo"}, TR::Source({{2, 4}})},
+  {{"getseuserbyname"}, TR::Source({{1, 2}})},

gamesh411 wrote:
> steakhal wrote:
> > In what cases can this function introduce taint?
> The getnameinfo converts from
> ```
> struct sockaddr_in {
> sa_family_tsin_family; /* address family: AF_INET */
> in_port_t  sin_port;   /* port in network byte order */
> struct in_addr sin_addr;   /* internet address */
> };
> 
> /* Internet address */
> struct in_addr {
> uint32_t   s_addr; /* address in network byte order */
> };
> ```
> to hostname and servername strings.
> One could argue that by crafting a specific IP address, that  is known to 
> resolve to a specific hostname in the running environment could lead an 
> attacker injecting a chosen (in some circumstances arbitrary) string into the 
> code at the point of this function.
> 
> I know this is a bit contrived, and more on the cybersecurity side of things, 
> so I am not sure whether to add this here, or add this in a specific checker, 
> or just leave altogether. Please share your opinion about this.
Let it be, I don't mind. We will remove it if we find some FPs for this.



Comment at: clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp:560
+  {{"readlink"}, TR::Source({{1, ReturnValueIndex}})},
+  {{"readlinkat"}, TR::Source({{1, ReturnValueIndex}})},
+  {{"get_current_dir_name"}, TR::Source({{ReturnValueIndex}})},

`int readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz);`



Comment at: clang/test/Analysis/taint-generic.c:372
+int _IO_getc(_IO_FILE *__fp);
+int test_IO_getc(_IO_FILE *fp) {
+  char c = _IO_getc(fp);

Please, also rename this test case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120236

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


[PATCH] D120333: [NFC][Lexer] Make access to LangOpts more consistent

2022-02-23 Thread Dawid Jurczak via Phabricator via cfe-commits
yurai007 added a comment.

Mentioned follow-up: https://reviews.llvm.org/D120404


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120333

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


[PATCH] D120375: Trim unnecessary component/library dependencies.

2022-02-23 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

Mostly a review of the clangd changes, I am not familiar with all the other 
parts (and not necessarily everyone will be) hence some explicit testing 
results would be great.
Also please upload the patch with full context.




Comment at: clang-tools-extra/clangd/CMakeLists.txt:41
-  Support
-  AllTargetsInfos
-  FrontendOpenMP

clangd actually requires `AllTargetsInfos` so that it can display detailed 
semantic information like bitwidth of certain types. not just on the final 
binary (as I see you've included this on the tool/CMakeLists.txt), there are 
also tests that depend on it.



Comment at: clang-tools-extra/clangd/indexer/CMakeLists.txt:11
   PRIVATE
-  clangAST
   clangBasic

these are all required dependencies of clangd-indexer. i suppose you're getting 
rid of these as they're transitively linked in by clangDeamon, but I remember 
some build configurations (shared lib builds) still requiring these to be 
present at these levels as well. i might be wrong, but it would be better to 
show some explicit testing results claiming these are not causing breakages (as 
Mehdi pointed out).



Comment at: clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt:35
   clangdSupport
-  clangFormat
   clangLex

this might require extra cleanups on the headers of some sources.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120375

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


[PATCH] D113775: [clang][modules] Umbrella with missing submodule: unify implicit & explicit

2022-02-23 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 abandoned this revision.
jansvoboda11 added a comment.

Abandoning, since we have a better solution: disable implicit module maps in 
explicit modules builds.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113775

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


[PATCH] D112916: Confusable identifiers detection

2022-02-23 Thread serge via Phabricator via cfe-commits
serge-sans-paille updated this revision to Diff 410776.
serge-sans-paille added a comment.

Rebased on `main` branch and (should) fix @aaron.ballman portability issue.


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

https://reviews.llvm.org/D112916

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/ConfusableTable/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/ConfusableTable/build_confusable_table.cpp
  clang-tools-extra/clang-tidy/misc/ConfusableTable/confusables.txt
  clang-tools-extra/clang-tidy/misc/Homoglyph.cpp
  clang-tools-extra/clang-tidy/misc/Homoglyph.h
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/misc-homoglyph.rst
  clang-tools-extra/test/clang-tidy/checkers/misc-homoglyph.cpp

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


Re: [PATCH] D120333: [NFC][Lexer] Make access to LangOpts more consistent

2022-02-23 Thread Serge Guelton via cfe-commits
Sure!
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

2022-02-23 Thread Dawid Jurczak via Phabricator via cfe-commits
yurai007 added inline comments.



Comment at: clang/lib/Lex/ModuleMap.cpp:1617
 const char *Start = SpellingBuffer.data();
-unsigned Length =
-Lexer::getSpelling(LToken, Start, SourceMgr, L.getLangOpts());
+unsigned Length = L.getSpelling(LToken, Start, SourceMgr);
 uint64_t Value;

That's interesting. ModuleMapParser::Map already has LangOpts member (which is 
const LangOptions &). If we could prove there are equal to Lexer::LangOpts 
after: https://reviews.llvm.org/D120334 maybe it would be possible to not 
introduce Lexer::getSpelling convenience method at all.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120404

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


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

2022-02-23 Thread serge via Phabricator via cfe-commits
serge-sans-paille accepted this revision.
serge-sans-paille added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/include/clang/Lex/Lexer.h:313
 
+  /// getSpelling - This is non-staic variant of getSpelling method which
+  /// doesn't require passing LangOpts argument.

nit: *static*


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120404

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


[PATCH] D119926: [Clang][AArch64] Enable _Float16 _Complex type

2022-02-23 Thread Peter Waller via Phabricator via cfe-commits
peterwaller-arm added inline comments.



Comment at: clang/test/CodeGen/aarch64-complex-half-math.c:3
+// RUN: %clang_cc1 %s -emit-llvm -triple aarch64-unknown-unknown -o - | 
FileCheck %s --check-prefix=AARCH64
+// REQUIRES: aarch64-registered-target
+

aaron.ballman wrote:
> There's nothing AArch64-specific about the change, so I'd expect some more 
> general codegen tests.
> 
> Actually, I took a look to see what calls 
> `getFloatingTypeOfSizeWithinDomain()` and I can't find any callers of that. 
> Do you have a test case where you were hitting that particular unreachable?
Thanks for your observation @aaron.ballman.

It appears this has been working since D105331, which enabled it for X86.

Unless I'm missing something, the function in question appears to have been 
unused since 2010 (the last use was removed in 
d005ac937e4c08e0c607ddc42708f8bf2064c243 by @rjmccall), I presume 
`getFloatingTypeOfSizeWithinDomain` should be removed then.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119926

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


[PATCH] D120395: [X86] Prohibit arithmatic operations on type `__bfloat16`

2022-02-23 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added a comment.

In D120395#3340041 , @RKSimon wrote:

> but its still OK to perform arithmetic with __m128bh ? 
> https://simd.godbolt.org/z/Ef59Ws4M3

Good point! I'd think the define of `__m128bh` is wrong direction. We should 
use `__m128i` like we doing with f16c intrinsics and reserve `__m128bh` for ABI 
type like we doing with avx512fp16.
I tried to warn for it using `deprecated` but it didn't report warning at all. 
Any thought?

  diff --git a/clang/lib/Headers/avx512bf16intrin.h 
b/clang/lib/Headers/avx512bf16intrin.h
  index 54f0cb9cfbf1..2f9cda6b32f2 100644
  --- a/clang/lib/Headers/avx512bf16intrin.h
  +++ b/clang/lib/Headers/avx512bf16intrin.h
  @@ -13,8 +13,10 @@
   #ifndef __AVX512BF16INTRIN_H
   #define __AVX512BF16INTRIN_H
  
  -typedef short __m512bh __attribute__((__vector_size__(64), __aligned__(64)));
  -typedef short __m256bh __attribute__((__vector_size__(32), __aligned__(32)));
  +typedef short __m512bh __attribute__((__vector_size__(64), __aligned__(64),
  +  deprecated("use __m512i instead")));
  +typedef short __m256bh __attribute__((__vector_size__(32), __aligned__(32),
  +  deprecated("use __m256i instead")));
  
   /// \typedef __bfloat16
   ///A target specific type to represent the storage only brain 
floating-point
  diff --git a/clang/lib/Headers/avx512vlbf16intrin.h 
b/clang/lib/Headers/avx512vlbf16intrin.h
  index d42f8eb0f0f5..0e47a930ebd0 100644
  --- a/clang/lib/Headers/avx512vlbf16intrin.h
  +++ b/clang/lib/Headers/avx512vlbf16intrin.h
  @@ -13,7 +13,8 @@
   #ifndef __AVX512VLBF16INTRIN_H
   #define __AVX512VLBF16INTRIN_H
  
  -typedef short __m128bh __attribute__((__vector_size__(16), __aligned__(16)));
  +typedef short __m128bh __attribute__((__vector_size__(16), __aligned__(16),
  +  deprecated("use __m128i instead")));
  
   #define __DEFAULT_FN_ATTRS128 \
 __attribute__((__always_inline__, __nodebug__, \


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120395

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


[clang] 2f300d3 - [clang][driver][wasm] Fix libstdc++ target-dependent include dir

2022-02-23 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2022-02-23T14:38:34+01:00
New Revision: 2f300d34decba547dd07f5cd6034a6b2b2ca11a2

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

LOG: [clang][driver][wasm] Fix libstdc++ target-dependent include dir

The triple goes after the gcc version, not before. Also add the
/backward version.

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/WebAssembly.cpp
clang/test/Driver/wasm-toolchain.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/WebAssembly.cpp 
b/clang/lib/Driver/ToolChains/WebAssembly.cpp
index 292cf4d66971f..c5e4d569793c3 100644
--- a/clang/lib/Driver/ToolChains/WebAssembly.cpp
+++ b/clang/lib/Driver/ToolChains/WebAssembly.cpp
@@ -528,10 +528,12 @@ void WebAssembly::addLibStdCXXIncludePaths(
 
   // First add the per-target include path if the OS is known.
   if (IsKnownOs) {
-std::string TargetDir = LibPath + "/" + MultiarchTriple + "/c++/" + 
Version;
+std::string TargetDir = LibPath + "/c++/" + Version + "/" + 
MultiarchTriple;
 addSystemInclude(DriverArgs, CC1Args, TargetDir);
   }
 
   // Second add the generic one.
   addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version);
+  // Third the backward one.
+  addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version + 
"/backward");
 }

diff  --git a/clang/test/Driver/wasm-toolchain.cpp 
b/clang/test/Driver/wasm-toolchain.cpp
index 4a95860413dd9..3ff6a2cd53282 100644
--- a/clang/test/Driver/wasm-toolchain.cpp
+++ b/clang/test/Driver/wasm-toolchain.cpp
@@ -80,8 +80,9 @@
 // COMPILE_STDCXX: clang{{.*}}" "-cc1"
 // COMPILE_STDCXX: "-resource-dir" "[[RESOURCE_DIR:[^"]*]]"
 // COMPILE_STDCXX: "-isysroot" "[[SYSROOT:[^"]+]]"
-// COMPILE_STDCXX: "-internal-isystem" 
"[[SYSROOT:[^"]+]]/include/wasm32-wasi/c++/4.8"
+// COMPILE_STDCXX: "-internal-isystem" 
"[[SYSROOT:[^"]+]]/include/c++/4.8/wasm32-wasi"
 // COMPILE_STDCXX: "-internal-isystem" "[[SYSROOT:[^"]+]]/include/c++/4.8"
+// COMPILE_STDCXX: "-internal-isystem" 
"[[SYSROOT:[^"]+]]/include/c++/4.8/backward"
 // COMPILE_STDCXX: "-internal-isystem" "[[RESOURCE_DIR]]{{(/|)}}include"
 // COMPILE_STDCXX: "-internal-isystem" "[[SYSROOT:[^"]+]]/include/wasm32-wasi"
 // COMPILE_STDCXX: "-internal-isystem" "[[SYSROOT:[^"]+]]/include"



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


[PATCH] D120251: [clang][driver][wasm] Fix libstdc++ target-dependent include dir

2022-02-23 Thread Timm Bäder 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 rG2f300d34decb: [clang][driver][wasm] Fix libstdc++ 
target-dependent include dir (authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120251

Files:
  clang/lib/Driver/ToolChains/WebAssembly.cpp
  clang/test/Driver/wasm-toolchain.cpp


Index: clang/test/Driver/wasm-toolchain.cpp
===
--- clang/test/Driver/wasm-toolchain.cpp
+++ clang/test/Driver/wasm-toolchain.cpp
@@ -80,8 +80,9 @@
 // COMPILE_STDCXX: clang{{.*}}" "-cc1"
 // COMPILE_STDCXX: "-resource-dir" "[[RESOURCE_DIR:[^"]*]]"
 // COMPILE_STDCXX: "-isysroot" "[[SYSROOT:[^"]+]]"
-// COMPILE_STDCXX: "-internal-isystem" 
"[[SYSROOT:[^"]+]]/include/wasm32-wasi/c++/4.8"
+// COMPILE_STDCXX: "-internal-isystem" 
"[[SYSROOT:[^"]+]]/include/c++/4.8/wasm32-wasi"
 // COMPILE_STDCXX: "-internal-isystem" "[[SYSROOT:[^"]+]]/include/c++/4.8"
+// COMPILE_STDCXX: "-internal-isystem" 
"[[SYSROOT:[^"]+]]/include/c++/4.8/backward"
 // COMPILE_STDCXX: "-internal-isystem" "[[RESOURCE_DIR]]{{(/|)}}include"
 // COMPILE_STDCXX: "-internal-isystem" "[[SYSROOT:[^"]+]]/include/wasm32-wasi"
 // COMPILE_STDCXX: "-internal-isystem" "[[SYSROOT:[^"]+]]/include"
Index: clang/lib/Driver/ToolChains/WebAssembly.cpp
===
--- clang/lib/Driver/ToolChains/WebAssembly.cpp
+++ clang/lib/Driver/ToolChains/WebAssembly.cpp
@@ -528,10 +528,12 @@
 
   // First add the per-target include path if the OS is known.
   if (IsKnownOs) {
-std::string TargetDir = LibPath + "/" + MultiarchTriple + "/c++/" + 
Version;
+std::string TargetDir = LibPath + "/c++/" + Version + "/" + 
MultiarchTriple;
 addSystemInclude(DriverArgs, CC1Args, TargetDir);
   }
 
   // Second add the generic one.
   addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version);
+  // Third the backward one.
+  addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version + 
"/backward");
 }


Index: clang/test/Driver/wasm-toolchain.cpp
===
--- clang/test/Driver/wasm-toolchain.cpp
+++ clang/test/Driver/wasm-toolchain.cpp
@@ -80,8 +80,9 @@
 // COMPILE_STDCXX: clang{{.*}}" "-cc1"
 // COMPILE_STDCXX: "-resource-dir" "[[RESOURCE_DIR:[^"]*]]"
 // COMPILE_STDCXX: "-isysroot" "[[SYSROOT:[^"]+]]"
-// COMPILE_STDCXX: "-internal-isystem" "[[SYSROOT:[^"]+]]/include/wasm32-wasi/c++/4.8"
+// COMPILE_STDCXX: "-internal-isystem" "[[SYSROOT:[^"]+]]/include/c++/4.8/wasm32-wasi"
 // COMPILE_STDCXX: "-internal-isystem" "[[SYSROOT:[^"]+]]/include/c++/4.8"
+// COMPILE_STDCXX: "-internal-isystem" "[[SYSROOT:[^"]+]]/include/c++/4.8/backward"
 // COMPILE_STDCXX: "-internal-isystem" "[[RESOURCE_DIR]]{{(/|)}}include"
 // COMPILE_STDCXX: "-internal-isystem" "[[SYSROOT:[^"]+]]/include/wasm32-wasi"
 // COMPILE_STDCXX: "-internal-isystem" "[[SYSROOT:[^"]+]]/include"
Index: clang/lib/Driver/ToolChains/WebAssembly.cpp
===
--- clang/lib/Driver/ToolChains/WebAssembly.cpp
+++ clang/lib/Driver/ToolChains/WebAssembly.cpp
@@ -528,10 +528,12 @@
 
   // First add the per-target include path if the OS is known.
   if (IsKnownOs) {
-std::string TargetDir = LibPath + "/" + MultiarchTriple + "/c++/" + Version;
+std::string TargetDir = LibPath + "/c++/" + Version + "/" + MultiarchTriple;
 addSystemInclude(DriverArgs, CC1Args, TargetDir);
   }
 
   // Second add the generic one.
   addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version);
+  // Third the backward one.
+  addSystemInclude(DriverArgs, CC1Args, LibPath + "/c++/" + Version + "/backward");
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D113880: [clang][modules] Infer framework modules in explicit builds

2022-02-23 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 410785.
jansvoboda11 edited the summary of this revision.
jansvoboda11 added a comment.

Remove changes related to dependency scanning


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113880

Files:
  clang/include/clang/Lex/ModuleMap.h
  clang/lib/Frontend/FrontendAction.cpp
  clang/test/Modules/explicit-build-inferred.cpp


Index: clang/test/Modules/explicit-build-inferred.cpp
===
--- clang/test/Modules/explicit-build-inferred.cpp
+++ clang/test/Modules/explicit-build-inferred.cpp
@@ -1,11 +1,10 @@
 // RUN: rm -rf %t && mkdir %t
 //
-// RUN: %clang_cc1 -fmodules -fno-implicit-modules -fimplicit-module-maps \
+// RUN: %clang_cc1 -fmodules -fno-implicit-modules \
 // RUN:   -emit-module -x c++ 
%S/Inputs/explicit-build-inferred/frameworks/module.modulemap \
 // RUN:   -fmodule-name=Inferred -o %t/Inferred.pcm -F 
%S/Inputs/explicit-build-inferred/frameworks
 //
 // RUN: %clang_cc1 -fmodules -fno-implicit-modules -fsyntax-only %s \
-// RUN:   
-fmodule-map-file=%S/Inputs/explicit-build-inferred/frameworks/module.modulemap 
\
 // RUN:   -fmodule-file=%t/Inferred.pcm -F 
%S/Inputs/explicit-build-inferred/frameworks
 
 #include 
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -465,6 +465,15 @@
   if (SrcMgr.getBufferOrFake(ModuleMapID).getBufferSize() == Offset)
 Offset = 0;
 
+  // Infer framework module if possible.
+  if (HS.getModuleMap().canInferFrameworkModule(ModuleMap->getDir())) {
+SmallString<128> InferredFrameworkPath = ModuleMap->getDir()->getName();
+llvm::sys::path::append(InferredFrameworkPath,
+CI.getLangOpts().ModuleName + ".framework");
+if (auto Dir = CI.getFileManager().getDirectory(InferredFrameworkPath))
+  (void)HS.getModuleMap().inferFrameworkModule(*Dir, IsSystem, nullptr);
+  }
+
   return false;
 }
 
Index: clang/include/clang/Lex/ModuleMap.h
===
--- clang/include/clang/Lex/ModuleMap.h
+++ clang/include/clang/Lex/ModuleMap.h
@@ -584,6 +584,12 @@
 return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
   }
 
+  /// Check whether a framework module can be inferred in the given directory.
+  bool canInferFrameworkModule(const DirectoryEntry *Dir) const {
+auto It = InferredDirectories.find(Dir);
+return It != InferredDirectories.end() && It->getSecond().InferModules;
+  }
+
   /// Retrieve the module map file containing the definition of the given
   /// module.
   ///


Index: clang/test/Modules/explicit-build-inferred.cpp
===
--- clang/test/Modules/explicit-build-inferred.cpp
+++ clang/test/Modules/explicit-build-inferred.cpp
@@ -1,11 +1,10 @@
 // RUN: rm -rf %t && mkdir %t
 //
-// RUN: %clang_cc1 -fmodules -fno-implicit-modules -fimplicit-module-maps \
+// RUN: %clang_cc1 -fmodules -fno-implicit-modules \
 // RUN:   -emit-module -x c++ %S/Inputs/explicit-build-inferred/frameworks/module.modulemap \
 // RUN:   -fmodule-name=Inferred -o %t/Inferred.pcm -F %S/Inputs/explicit-build-inferred/frameworks
 //
 // RUN: %clang_cc1 -fmodules -fno-implicit-modules -fsyntax-only %s \
-// RUN:   -fmodule-map-file=%S/Inputs/explicit-build-inferred/frameworks/module.modulemap \
 // RUN:   -fmodule-file=%t/Inferred.pcm -F %S/Inputs/explicit-build-inferred/frameworks
 
 #include 
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -465,6 +465,15 @@
   if (SrcMgr.getBufferOrFake(ModuleMapID).getBufferSize() == Offset)
 Offset = 0;
 
+  // Infer framework module if possible.
+  if (HS.getModuleMap().canInferFrameworkModule(ModuleMap->getDir())) {
+SmallString<128> InferredFrameworkPath = ModuleMap->getDir()->getName();
+llvm::sys::path::append(InferredFrameworkPath,
+CI.getLangOpts().ModuleName + ".framework");
+if (auto Dir = CI.getFileManager().getDirectory(InferredFrameworkPath))
+  (void)HS.getModuleMap().inferFrameworkModule(*Dir, IsSystem, nullptr);
+  }
+
   return false;
 }
 
Index: clang/include/clang/Lex/ModuleMap.h
===
--- clang/include/clang/Lex/ModuleMap.h
+++ clang/include/clang/Lex/ModuleMap.h
@@ -584,6 +584,12 @@
 return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
   }
 
+  /// Check whether a framework module can be inferred in the given directory.
+  bool canInferFrameworkModule(const DirectoryEntry *Dir) const {
+auto It = InferredDirectories.find(Dir);
+return It != InferredDir

[clang] 27d9a58 - [clang][modules] Infer framework modules in explicit builds

2022-02-23 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-02-23T14:46:23+01:00
New Revision: 27d9a58407c44c8bb3fe7b94ff8d3b9bea25afc4

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

LOG: [clang][modules] Infer framework modules in explicit builds

This patch enables inferring framework modules in explicit builds in all 
contexts. Until now, inferring framework modules only worked with 
`-fimplicit-module-maps` due to this block of code:

```
// HeaderSearch::loadFrameworkModule
  case LMM_InvalidModuleMap:
// Try to infer a module map from the framework directory.
if (HSOpts->ImplicitModuleMaps)
  ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
break;
```

Reviewed By: Bigcheese

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

Added: 


Modified: 
clang/include/clang/Lex/ModuleMap.h
clang/lib/Frontend/FrontendAction.cpp
clang/test/Modules/explicit-build-inferred.cpp

Removed: 




diff  --git a/clang/include/clang/Lex/ModuleMap.h 
b/clang/include/clang/Lex/ModuleMap.h
index 08c61a5dc5607..26169ae9cee95 100644
--- a/clang/include/clang/Lex/ModuleMap.h
+++ b/clang/include/clang/Lex/ModuleMap.h
@@ -584,6 +584,12 @@ class ModuleMap {
 return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
   }
 
+  /// Check whether a framework module can be inferred in the given directory.
+  bool canInferFrameworkModule(const DirectoryEntry *Dir) const {
+auto It = InferredDirectories.find(Dir);
+return It != InferredDirectories.end() && It->getSecond().InferModules;
+  }
+
   /// Retrieve the module map file containing the definition of the given
   /// module.
   ///

diff  --git a/clang/lib/Frontend/FrontendAction.cpp 
b/clang/lib/Frontend/FrontendAction.cpp
index 089f40b36089a..c5b9e80356db4 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -465,6 +465,15 @@ static bool loadModuleMapForModuleBuild(CompilerInstance 
&CI, bool IsSystem,
   if (SrcMgr.getBufferOrFake(ModuleMapID).getBufferSize() == Offset)
 Offset = 0;
 
+  // Infer framework module if possible.
+  if (HS.getModuleMap().canInferFrameworkModule(ModuleMap->getDir())) {
+SmallString<128> InferredFrameworkPath = ModuleMap->getDir()->getName();
+llvm::sys::path::append(InferredFrameworkPath,
+CI.getLangOpts().ModuleName + ".framework");
+if (auto Dir = CI.getFileManager().getDirectory(InferredFrameworkPath))
+  (void)HS.getModuleMap().inferFrameworkModule(*Dir, IsSystem, nullptr);
+  }
+
   return false;
 }
 

diff  --git a/clang/test/Modules/explicit-build-inferred.cpp 
b/clang/test/Modules/explicit-build-inferred.cpp
index 2ee585692a687..42a22fd136b7b 100644
--- a/clang/test/Modules/explicit-build-inferred.cpp
+++ b/clang/test/Modules/explicit-build-inferred.cpp
@@ -1,11 +1,10 @@
 // RUN: rm -rf %t && mkdir %t
 //
-// RUN: %clang_cc1 -fmodules -fno-implicit-modules -fimplicit-module-maps \
+// RUN: %clang_cc1 -fmodules -fno-implicit-modules \
 // RUN:   -emit-module -x c++ 
%S/Inputs/explicit-build-inferred/frameworks/module.modulemap \
 // RUN:   -fmodule-name=Inferred -o %t/Inferred.pcm -F 
%S/Inputs/explicit-build-inferred/frameworks
 //
 // RUN: %clang_cc1 -fmodules -fno-implicit-modules -fsyntax-only %s \
-// RUN:   
-fmodule-map-file=%S/Inputs/explicit-build-inferred/frameworks/module.modulemap 
\
 // RUN:   -fmodule-file=%t/Inferred.pcm -F 
%S/Inputs/explicit-build-inferred/frameworks
 
 #include 



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


[PATCH] D113880: [clang][modules] Infer framework modules in explicit builds

2022-02-23 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG27d9a58407c4: [clang][modules] Infer framework modules in 
explicit builds (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113880

Files:
  clang/include/clang/Lex/ModuleMap.h
  clang/lib/Frontend/FrontendAction.cpp
  clang/test/Modules/explicit-build-inferred.cpp


Index: clang/test/Modules/explicit-build-inferred.cpp
===
--- clang/test/Modules/explicit-build-inferred.cpp
+++ clang/test/Modules/explicit-build-inferred.cpp
@@ -1,11 +1,10 @@
 // RUN: rm -rf %t && mkdir %t
 //
-// RUN: %clang_cc1 -fmodules -fno-implicit-modules -fimplicit-module-maps \
+// RUN: %clang_cc1 -fmodules -fno-implicit-modules \
 // RUN:   -emit-module -x c++ 
%S/Inputs/explicit-build-inferred/frameworks/module.modulemap \
 // RUN:   -fmodule-name=Inferred -o %t/Inferred.pcm -F 
%S/Inputs/explicit-build-inferred/frameworks
 //
 // RUN: %clang_cc1 -fmodules -fno-implicit-modules -fsyntax-only %s \
-// RUN:   
-fmodule-map-file=%S/Inputs/explicit-build-inferred/frameworks/module.modulemap 
\
 // RUN:   -fmodule-file=%t/Inferred.pcm -F 
%S/Inputs/explicit-build-inferred/frameworks
 
 #include 
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -465,6 +465,15 @@
   if (SrcMgr.getBufferOrFake(ModuleMapID).getBufferSize() == Offset)
 Offset = 0;
 
+  // Infer framework module if possible.
+  if (HS.getModuleMap().canInferFrameworkModule(ModuleMap->getDir())) {
+SmallString<128> InferredFrameworkPath = ModuleMap->getDir()->getName();
+llvm::sys::path::append(InferredFrameworkPath,
+CI.getLangOpts().ModuleName + ".framework");
+if (auto Dir = CI.getFileManager().getDirectory(InferredFrameworkPath))
+  (void)HS.getModuleMap().inferFrameworkModule(*Dir, IsSystem, nullptr);
+  }
+
   return false;
 }
 
Index: clang/include/clang/Lex/ModuleMap.h
===
--- clang/include/clang/Lex/ModuleMap.h
+++ clang/include/clang/Lex/ModuleMap.h
@@ -584,6 +584,12 @@
 return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
   }
 
+  /// Check whether a framework module can be inferred in the given directory.
+  bool canInferFrameworkModule(const DirectoryEntry *Dir) const {
+auto It = InferredDirectories.find(Dir);
+return It != InferredDirectories.end() && It->getSecond().InferModules;
+  }
+
   /// Retrieve the module map file containing the definition of the given
   /// module.
   ///


Index: clang/test/Modules/explicit-build-inferred.cpp
===
--- clang/test/Modules/explicit-build-inferred.cpp
+++ clang/test/Modules/explicit-build-inferred.cpp
@@ -1,11 +1,10 @@
 // RUN: rm -rf %t && mkdir %t
 //
-// RUN: %clang_cc1 -fmodules -fno-implicit-modules -fimplicit-module-maps \
+// RUN: %clang_cc1 -fmodules -fno-implicit-modules \
 // RUN:   -emit-module -x c++ %S/Inputs/explicit-build-inferred/frameworks/module.modulemap \
 // RUN:   -fmodule-name=Inferred -o %t/Inferred.pcm -F %S/Inputs/explicit-build-inferred/frameworks
 //
 // RUN: %clang_cc1 -fmodules -fno-implicit-modules -fsyntax-only %s \
-// RUN:   -fmodule-map-file=%S/Inputs/explicit-build-inferred/frameworks/module.modulemap \
 // RUN:   -fmodule-file=%t/Inferred.pcm -F %S/Inputs/explicit-build-inferred/frameworks
 
 #include 
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -465,6 +465,15 @@
   if (SrcMgr.getBufferOrFake(ModuleMapID).getBufferSize() == Offset)
 Offset = 0;
 
+  // Infer framework module if possible.
+  if (HS.getModuleMap().canInferFrameworkModule(ModuleMap->getDir())) {
+SmallString<128> InferredFrameworkPath = ModuleMap->getDir()->getName();
+llvm::sys::path::append(InferredFrameworkPath,
+CI.getLangOpts().ModuleName + ".framework");
+if (auto Dir = CI.getFileManager().getDirectory(InferredFrameworkPath))
+  (void)HS.getModuleMap().inferFrameworkModule(*Dir, IsSystem, nullptr);
+  }
+
   return false;
 }
 
Index: clang/include/clang/Lex/ModuleMap.h
===
--- clang/include/clang/Lex/ModuleMap.h
+++ clang/include/clang/Lex/ModuleMap.h
@@ -584,6 +584,12 @@
 return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
   }
 
+  /// Check whether a framework module can be inferred in the given directory.
+  bool canInferFrameworkModule(const DirectoryEntry *Dir) const {
+ 

[PATCH] D120374: [clang-format] Do not insert space after new/delete keywords in C function declarations

2022-02-23 Thread Luis Penagos via Phabricator via cfe-commits
penagos updated this revision to Diff 410788.
penagos added a comment.

Add missing space in unittest.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120374

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
@@ -9919,6 +9919,11 @@
   verifyFormat("void operator new(void *foo) ATTRIB;");
   verifyFormat("void operator delete[](void *foo) ATTRIB;");
   verifyFormat("void operator delete(void *ptr) noexcept;");
+
+  EXPECT_EQ("void new(link p);\n"
+"void delete(link p);\n",
+format("void new (link p);\n"
+   "void delete (link p);\n"));
 }
 
 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3299,11 +3299,15 @@
   if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch))
 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
spaceRequiredBeforeParens(Right);
-  if (Left.isOneOf(tok::kw_new, tok::kw_delete) ||
-  (Left.is(tok::r_square) && Left.MatchingParen &&
-   Left.MatchingParen->Previous &&
-   Left.MatchingParen->Previous->is(tok::kw_delete)))
-return Style.SpaceBeforeParens != FormatStyle::SBPO_Never ||
+  if (Left.isOneOf(tok::kw_new, tok::kw_delete))
+return ((!Line.MightBeFunctionDecl || !Left.Previous) &&
+Style.SpaceBeforeParens != FormatStyle::SBPO_Never) ||
+   spaceRequiredBeforeParens(Right);
+
+  if (Left.is(tok::r_square) && Left.MatchingParen &&
+  Left.MatchingParen->Previous &&
+  Left.MatchingParen->Previous->is(tok::kw_delete))
+return (Style.SpaceBeforeParens != FormatStyle::SBPO_Never) ||
spaceRequiredBeforeParens(Right);
 }
 if (Line.Type != LT_PreprocessorDirective &&


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -9919,6 +9919,11 @@
   verifyFormat("void operator new(void *foo) ATTRIB;");
   verifyFormat("void operator delete[](void *foo) ATTRIB;");
   verifyFormat("void operator delete(void *ptr) noexcept;");
+
+  EXPECT_EQ("void new(link p);\n"
+"void delete(link p);\n",
+format("void new (link p);\n"
+   "void delete (link p);\n"));
 }
 
 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3299,11 +3299,15 @@
   if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch))
 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
spaceRequiredBeforeParens(Right);
-  if (Left.isOneOf(tok::kw_new, tok::kw_delete) ||
-  (Left.is(tok::r_square) && Left.MatchingParen &&
-   Left.MatchingParen->Previous &&
-   Left.MatchingParen->Previous->is(tok::kw_delete)))
-return Style.SpaceBeforeParens != FormatStyle::SBPO_Never ||
+  if (Left.isOneOf(tok::kw_new, tok::kw_delete))
+return ((!Line.MightBeFunctionDecl || !Left.Previous) &&
+Style.SpaceBeforeParens != FormatStyle::SBPO_Never) ||
+   spaceRequiredBeforeParens(Right);
+
+  if (Left.is(tok::r_square) && Left.MatchingParen &&
+  Left.MatchingParen->Previous &&
+  Left.MatchingParen->Previous->is(tok::kw_delete))
+return (Style.SpaceBeforeParens != FormatStyle::SBPO_Never) ||
spaceRequiredBeforeParens(Right);
 }
 if (Line.Type != LT_PreprocessorDirective &&
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D120374: [clang-format] Do not insert space after new/delete keywords in C function declarations

2022-02-23 Thread Luis Penagos via Phabricator via cfe-commits
penagos marked an inline comment as done.
penagos added a comment.

In D120374#3339554 , @curdeius wrote:

> In D120374#3339337 , @penagos wrote:
>
>> Though it's still unclear to me whether or not it'd make more sense to 
>> continue to pursue a change to introduce `C` as a language. Thoughts?
>
> I prefer your current approach (and there should be not that many cases that 
> we need a special treatment for C).

Makes sense. I'll also need someone to commit on my behalf:

- Luis Penagos
- l...@penagos.co

Thanks!




Comment at: clang/unittests/Format/FormatTest.cpp:9926
+format("void new (link p);\n"
+   "void delete(link p);\n"));
 }

curdeius wrote:
> Why there's no space after `delete` in the input?
Whoops, good catch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120374

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


RE: [clang] 4bafe65 - Add support for floating-point option `ffp-eval-method` and for

2022-02-23 Thread Ammarguellat, Zahira via cfe-commits
https://reviews.llvm.org/D109239

-Original Message-
From: Roman Lebedev  
Sent: Tuesday, February 15, 2022 5:26 PM
To: Ammarguellat, Zahira ; Zahira Ammarguellat 

Cc: cfe-commits@lists.llvm.org
Subject: Re: [clang] 4bafe65 - Add support for floating-point option 
`ffp-eval-method` and for

Where was this reviewed?

On Wed, Feb 16, 2022 at 12:59 AM Zahira Ammarguellat via cfe-commits
 wrote:
>
>
> Author: Zahira Ammarguellat
> Date: 2022-02-15T13:59:27-08:00
> New Revision: 4bafe65c2b2f1ce745894a509a6d80c87fb1c335
>
> URL: 
> https://github.com/llvm/llvm-project/commit/4bafe65c2b2f1ce745894a509a6d80c87fb1c335
> DIFF: 
> https://github.com/llvm/llvm-project/commit/4bafe65c2b2f1ce745894a509a6d80c87fb1c335.diff
>
> LOG: Add support for floating-point option `ffp-eval-method` and for
> `pragma clang fp eval_method`.
>
> Added:
> clang/test/CodeGen/X86/32bit-behavior-no-eval.c
> clang/test/CodeGen/X86/32bit-behavior.c
> clang/test/CodeGen/X86/fp-eval-method.c
> clang/test/CodeGen/flt_eval_macro.cpp
> clang/test/Preprocessor/flt_eval_macro.cpp
> clang/test/Sema/fp-eval-pragma.cpp
> clang/test/Sema/x86-eval-method.c
> clang/test/Sema/x86_64-eval-method.c
>
> Modified:
> clang/docs/LanguageExtensions.rst
> clang/docs/UsersManual.rst
> clang/include/clang/Basic/DiagnosticCommonKinds.td
> clang/include/clang/Basic/DiagnosticLexKinds.td
> clang/include/clang/Basic/FPOptions.def
> clang/include/clang/Basic/LangOptions.def
> clang/include/clang/Basic/LangOptions.h
> clang/include/clang/Basic/TargetInfo.h
> clang/include/clang/Driver/Options.td
> clang/include/clang/Lex/Preprocessor.h
> clang/include/clang/Parse/Parser.h
> clang/include/clang/Sema/Sema.h
> clang/lib/Basic/Targets/OSTargets.h
> clang/lib/Basic/Targets/X86.h
> clang/lib/Driver/ToolChains/Clang.cpp
> clang/lib/Frontend/InitPreprocessor.cpp
> clang/lib/Lex/PPMacroExpansion.cpp
> clang/lib/Parse/ParsePragma.cpp
> clang/lib/Parse/ParseStmt.cpp
> clang/lib/Sema/Sema.cpp
> clang/lib/Sema/SemaAttr.cpp
> clang/lib/Sema/SemaExpr.cpp
> clang/test/CodeGen/fp-floatcontrol-pragma.cpp
> clang/test/Preprocessor/init-aarch64.c
> clang/test/Preprocessor/init-arm.c
> clang/test/Preprocessor/init-mips.c
> clang/test/Preprocessor/init-ppc.c
> clang/test/Preprocessor/init-ppc64.c
> clang/test/Preprocessor/init-s390x.c
> clang/test/Preprocessor/init-v7k-compat.c
> clang/test/Preprocessor/init-x86.c
> clang/test/Preprocessor/init.c
>
> Removed:
>
>
>
> 
> diff  --git a/clang/docs/LanguageExtensions.rst 
> b/clang/docs/LanguageExtensions.rst
> index f45d88092eb4a..5249d3f3f7930 100644
> --- a/clang/docs/LanguageExtensions.rst
> +++ b/clang/docs/LanguageExtensions.rst
> @@ -3907,6 +3907,38 @@ A ``#pragma clang fp`` pragma may contain any number 
> of options:
>  ...
>}
>
> +``#pragma clang fp eval_method`` allows floating-point behavior to be 
> specified
> +for a section of the source code. This pragma can appear at file or namespace
> +scope, or at the start of a compound statement (excluding comments).
> +The pragma is active within the scope of the compound statement.
> +
> +When ``pragma clang fp eval_method(source)`` is enabled, the section of code
> +governed by the pragma behaves as though the command-line option
> +``-ffp-eval-method=source`` is enabled. Rounds intermediate results to
> +source-defined precision.
> +
> +When ``pragma clang fp eval_method(double)`` is enabled, the section of code
> +governed by the pragma behaves as though the command-line option
> +``-ffp-eval-method=double`` is enabled. Rounds intermediate results to
> +``double`` precision.
> +
> +When ``pragma clang fp eval_method(extended)`` is enabled, the section of 
> code
> +governed by the pragma behaves as though the command-line option
> +``-ffp-eval-method=extended`` is enabled. Rounds intermediate results to
> +target-dependent ``long double`` precision. In Win32 programming, for 
> instance,
> +the long double data type maps to the double, 64-bit precision data type.
> +
> +The full syntax this pragma supports is
> +``#pragma clang fp eval_method(source|double|extended)``.
> +
> +.. code-block:: c++
> +
> +  for(...) {
> +// The compiler will use long double as the floating-point evaluation
> +// method.
> +#pragma clang fp eval_method(extended)
> +a = b[i] * c[i] + e;
> +  }
>
>  The ``#pragma float_control`` pragma allows precise floating-point
>  semantics and floating-point exception behavior to be specified
>
> diff  --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
> index 1df96296cb8ac..70fee29ab2a84 100644
> --- a/clang/docs/UsersManual.rst
> +++ b/clang/docs/UsersManual.rst
> @@ -1566,6 +1566,22 @@ Note that floating-point operations performed as part 
> of constant initialization
> * ``maytrap``

[clang] 03dff12 - Revert "Revert "[clang][dataflow] Add support for global storage values""

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

Author: Stanislav Gatev
Date: 2022-02-23T13:57:34Z
New Revision: 03dff12197d15161ffc9ec7afeb9501551d6119e

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

LOG: Revert "Revert "[clang][dataflow] Add support for global storage values""

This reverts commit 169e1aba55bed9f7ffa000f9f170ab2defbc40b2.

It also fixes an incorrect assumption in `initGlobalVars`.

Added: 


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

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index af613c95bb8dc..bab20418a016a 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -49,6 +49,11 @@ enum class SkipPast {
 };
 
 /// Holds the state of the program (store and heap) at a given program point.
+///
+/// WARNING: Symbolic values that are created by the environment for static
+/// local and global variables are not currently invalidated on function calls.
+/// This is unsound and should be taken into account when designing dataflow
+/// analyses.
 class Environment {
 public:
   /// Supplements `Environment` with non-standard comparison and join

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index eca58b313761b..0fb341fd0bb05 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -22,6 +22,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/Support/ErrorHandling.h"
+#include 
 #include 
 #include 
 
@@ -56,10 +57,54 @@ static bool equivalentValues(QualType Type, Value *Val1, 
Value *Val2,
   return Model.compareEquivalent(Type, *Val1, *Val2);
 }
 
+/// Initializes a global storage value.
+static void initGlobalVar(const VarDecl &D, Environment &Env) {
+  if (!D.hasGlobalStorage() ||
+  Env.getStorageLocation(D, SkipPast::None) != nullptr)
+return;
+
+  auto &Loc = Env.createStorageLocation(D);
+  Env.setStorageLocation(D, Loc);
+  if (auto *Val = Env.createValue(D.getType()))
+Env.setValue(Loc, *Val);
+}
+
+/// Initializes a global storage value.
+static void initGlobalVar(const Decl &D, Environment &Env) {
+  if (auto *V = dyn_cast(&D))
+initGlobalVar(*V, Env);
+}
+
+/// Initializes global storage values that are declared or referenced from
+/// sub-statements of `S`.
+// FIXME: Add support for resetting globals after function calls to enable
+// the implementation of sound analyses.
+static void initGlobalVars(const Stmt &S, Environment &Env) {
+  for (auto *Child : S.children()) {
+if (Child != nullptr)
+  initGlobalVars(*Child, Env);
+  }
+
+  if (auto *DS = dyn_cast(&S)) {
+if (DS->isSingleDecl()) {
+  initGlobalVar(*DS->getSingleDecl(), Env);
+} else {
+  for (auto *D : DS->getDeclGroup())
+initGlobalVar(*D, Env);
+}
+  } else if (auto *E = dyn_cast(&S)) {
+initGlobalVar(*E->getDecl(), Env);
+  } else if (auto *E = dyn_cast(&S)) {
+initGlobalVar(*E->getMemberDecl(), Env);
+  }
+}
+
 Environment::Environment(DataflowAnalysisContext &DACtx,
  const DeclContext &DeclCtx)
 : Environment(DACtx) {
   if (const auto *FuncDecl = dyn_cast(&DeclCtx)) {
+assert(FuncDecl->getBody() != nullptr);
+initGlobalVars(*FuncDecl->getBody(), *this);
 for (const auto *ParamDecl : FuncDecl->parameters()) {
   assert(ParamDecl != nullptr);
   auto &ParamLoc = createStorageLocation(*ParamDecl);

diff  --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index cd9b8b0e454e4..4b5d23593a4bd 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -136,6 +136,11 @@ class TransferVisitor : public 
ConstStmtVisitor {
 // Group decls are converted into single decls in the CFG so the cast below
 // is safe.
 const auto &D = *cast(S->getSingleDecl());
+
+// Static local vars are already initialized in `Environment`.
+if (D.hasGlobalStorage())
+  return;
+
 auto &Loc = Env.createStorageLocation(D);
 Env.setStorageLocation(D, Loc);
 
@@ -291,6 +296,24 @@ class TransferVisitor : public 
ConstStmtVisitor {
 if (Member->isFunctionOrFunctionTemplate())
   return;
 
+if (auto *D = dyn_cast(Member)) {
+  if (D->hasGlobalStorage()) {
+auto *VarDeclLoc = Env.getStorageLocation(*D

[PATCH] D119165: [clang-tidy] Add processing lambda captures at bugprone-use-after-move check

2022-02-23 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added inline comments.



Comment at: clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp:403
hasArgument(0, declRefExpr().bind("arg")),
-   anyOf(hasAncestor(lambdaExpr().bind("containing-lambda")),
- hasAncestor(functionDecl().bind("containing-func"))),

I believe this can be done more simply.

IIUC, the root of the problem is that a std::move() in a lambda capture is 
being associated with the lambda, when in fact it should be associated with the 
function that contains the lambda.

This is because the `hasAncestor(lambdaExpr())` matches not just a `std::move` 
inside the body of the lambda, but also in captures.

I believe this can be solved simply by changing this line so that it only 
matches a `std::move` inside the body of the lambda, i.e. something like this:

```
hasAncestor(compoundStmt(hasParent(lambdaExpr().bind("containing-lambda"
```

This would then no longer match a `std::move` in a capture; the existing logic 
would instead associate it with the function that contains the lambda.
```



Comment at: clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp:418
+  forEachLambdaCapture(lambdaCapture(capturesVar(varDecl(
+  hasInitializer(expr(ignoringParenImpCasts(BaseMoveMatcher))),
+  AncestorMatcher);

sammccall wrote:
> This only matches when the initializer is exactly `std::move(x)`.
> Not e.g. if it's `SomeType(std::move(x))`. 
> 
> Former is probably the common case, but is this deliberate? If we're not sure 
> exactly which cases are safe, maybe add a FIXME?
If this isn't a deliberate restriction, can you add a test for this?



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp:1355
+// Check std::move usage inside lambda captures
+int lambdaCaptures() {
+  int a = 0;

Can  you put this test with the other tests for lambdas? My suggestion would be 
to insert it below line 418.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp:1356
+int lambdaCaptures() {
+  int a = 0;
+  int b = 0;

ivanmurashko wrote:
> sammccall wrote:
> > It's pretty interesting that use-after-move fires for ints!
> > 
> > Someone might decide to "fix" that though, so probably best to use A like 
> > the other tests.
> There is also another case that I want to address as a separate patch.
> ```
> void autoCapture() {
>   auto var = [](auto &&res) {
> auto f = [blk = std::move(res)]() {};
> return std::move(res);
>   };
> }
> ```
> This one is matched as `UnresolvedLookupExpr` and requires another modified 
> matcher
I assume the reason you don't want to address this case within this particular 
patch is that it requires a lot of additional code?



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp:1363
+// CHECK-NOTES: [[@LINE+4]]:14: warning: 'b' used after it was moved
+// CHECK-NOTES: [[@LINE-4]]:39: note: move occurred here
+return aa + bb + cc;

Can you put these `CHECK-NOTES` after the line `return a + b + c`?

The other tests put the `CHECK-NOTES` after the use, not the move, and it would 
be nice to be consistent with that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119165

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


[PATCH] D120334: [NFC][Lexer] Use more appropriate LangOptionsBase type for Lexer::LangOpts

2022-02-23 Thread Dawid Jurczak via Phabricator via cfe-commits
yurai007 added a comment.

In D120334#3339764 , 
@serge-sans-paille wrote:

> A small local test hints that using a ``SmallVector`` instead of a 
> ``std::vector`` also fixes the assembly bloat. I don't know if it's worth 
> considering as an alternative or  as an extra step.

Ok, I'm gonna try SmallVectors on top of this change. LangOptions is widely 
used so maybe it could bring some extra gains in places where vectors are 
indeed filled with more data.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120334

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


[PATCH] D120408: clang-format.el: Make clang-format work in indirect buffers.

2022-02-23 Thread Philipp via Phabricator via cfe-commits
phst created this revision.
phst added a reviewer: sammccall.
phst requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

In an indirect buffer, buffer-file-name is nil, so check the base buffer
instead.  This works fine in direct buffers where buffer-base-buffer returns
nil.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120408

Files:
  clang/tools/clang-format/clang-format.el


Index: clang/tools/clang-format/clang-format.el
===
--- clang/tools/clang-format/clang-format.el
+++ clang/tools/clang-format/clang-format.el
@@ -147,7 +147,7 @@
 (setq style clang-format-style))
 
   (unless assume-file-name
-(setq assume-file-name buffer-file-name))
+(setq assume-file-name (buffer-file-name (buffer-base-buffer
 
   (let ((file-start (clang-format--bufferpos-to-filepos start 'approximate
 'utf-8-unix))


Index: clang/tools/clang-format/clang-format.el
===
--- clang/tools/clang-format/clang-format.el
+++ clang/tools/clang-format/clang-format.el
@@ -147,7 +147,7 @@
 (setq style clang-format-style))
 
   (unless assume-file-name
-(setq assume-file-name buffer-file-name))
+(setq assume-file-name (buffer-file-name (buffer-base-buffer
 
   (let ((file-start (clang-format--bufferpos-to-filepos start 'approximate
 'utf-8-unix))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 841355c - Remove unused function; NFC

2022-02-23 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-02-23T09:08:27-05:00
New Revision: 841355c1e4e35fc02b5b171419979f5f9af0ebc8

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

LOG: Remove unused function; NFC

Added: 


Modified: 
clang/include/clang/AST/ASTContext.h
clang/lib/AST/ASTContext.cpp

Removed: 




diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 510c63962053b..f2d7060e6f3d3 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2758,14 +2758,6 @@ class ASTContext : public RefCountedBase {
   /// long double and double on AArch64 will return 0).
   int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const;
 
-  /// Return a real floating point or a complex type (based on
-  /// \p typeDomain/\p typeSize).
-  ///
-  /// \param typeDomain a real floating point or complex type.
-  /// \param typeSize a real floating point or complex type.
-  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
- QualType typeDomain) const;
-
   unsigned getTargetAddressSpace(QualType T) const;
 
   unsigned getTargetAddressSpace(Qualifiers Q) const;

diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index f29e90c05713c..f99c2b91b9232 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -6798,41 +6798,6 @@ static FloatingRank getFloatingRank(QualType T) {
   }
 }
 
-/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
-/// point or a complex type (based on typeDomain/typeSize).
-/// 'typeDomain' is a real floating point or complex type.
-/// 'typeSize' is a real floating point or complex type.
-QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
-   QualType Domain) const {
-  FloatingRank EltRank = getFloatingRank(Size);
-  if (Domain->isComplexType()) {
-switch (EltRank) {
-case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported");
-case Float16Rank:
-case HalfRank: llvm_unreachable("Complex half is not supported");
-case Ibm128Rank: return getComplexType(Ibm128Ty);
-case FloatRank:  return getComplexType(FloatTy);
-case DoubleRank: return getComplexType(DoubleTy);
-case LongDoubleRank: return getComplexType(LongDoubleTy);
-case Float128Rank:   return getComplexType(Float128Ty);
-}
-  }
-
-  assert(Domain->isRealFloatingType() && "Unknown domain!");
-  switch (EltRank) {
-  case Float16Rank:return HalfTy;
-  case BFloat16Rank:   return BFloat16Ty;
-  case HalfRank:   return HalfTy;
-  case FloatRank:  return FloatTy;
-  case DoubleRank: return DoubleTy;
-  case LongDoubleRank: return LongDoubleTy;
-  case Float128Rank:   return Float128Ty;
-  case Ibm128Rank:
-return Ibm128Ty;
-  }
-  llvm_unreachable("getFloatingRank(): illegal value for rank");
-}
-
 /// getFloatingTypeOrder - Compare the rank of the two specified floating
 /// point types, ignoring the domain of the type (i.e. 'double' ==
 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If



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


[PATCH] D120395: [X86] Prohibit arithmatic operations on type `__bfloat16`

2022-02-23 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added a comment.

In D120395#3340153 , @pengfei wrote:

> In D120395#3340041 , @RKSimon wrote:
>
>> but its still OK to perform arithmetic with __m128bh ? 
>> https://simd.godbolt.org/z/Ef59Ws4M3
>
> Good point! I'd think the define of `__m128bh` is wrong direction. We should 
> use `__m128i` like we doing with f16c intrinsics and reserve `__m128bh` for 
> ABI type like we doing with avx512fp16.
> I tried to warn for it using `deprecated` but it didn't report warning at 
> all. Any thought?
>
>   diff --git a/clang/lib/Headers/avx512bf16intrin.h 
> b/clang/lib/Headers/avx512bf16intrin.h
>   index 54f0cb9cfbf1..2f9cda6b32f2 100644
>   --- a/clang/lib/Headers/avx512bf16intrin.h
>   +++ b/clang/lib/Headers/avx512bf16intrin.h
>   @@ -13,8 +13,10 @@
>#ifndef __AVX512BF16INTRIN_H
>#define __AVX512BF16INTRIN_H
>   
>   -typedef short __m512bh __attribute__((__vector_size__(64), 
> __aligned__(64)));
>   -typedef short __m256bh __attribute__((__vector_size__(32), 
> __aligned__(32)));
>   +typedef short __m512bh __attribute__((__vector_size__(64), __aligned__(64),
>   +  deprecated("use __m512i instead")));
>   +typedef short __m256bh __attribute__((__vector_size__(32), __aligned__(32),
>   +  deprecated("use __m256i instead")));
>   
>/// \typedef __bfloat16
>///A target specific type to represent the storage only brain 
> floating-point
>   diff --git a/clang/lib/Headers/avx512vlbf16intrin.h 
> b/clang/lib/Headers/avx512vlbf16intrin.h
>   index d42f8eb0f0f5..0e47a930ebd0 100644
>   --- a/clang/lib/Headers/avx512vlbf16intrin.h
>   +++ b/clang/lib/Headers/avx512vlbf16intrin.h
>   @@ -13,7 +13,8 @@
>#ifndef __AVX512VLBF16INTRIN_H
>#define __AVX512VLBF16INTRIN_H
>   
>   -typedef short __m128bh __attribute__((__vector_size__(16), 
> __aligned__(16)));
>   +typedef short __m128bh __attribute__((__vector_size__(16), __aligned__(16),
>   +  deprecated("use __m128i instead")));
>   
>#define __DEFAULT_FN_ATTRS128 \
>  __attribute__((__always_inline__, __nodebug__, \

Sorry, it works.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120395

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


[PATCH] D119926: [Clang][AArch64] Enable _Float16 _Complex type

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



Comment at: clang/test/CodeGen/aarch64-complex-half-math.c:3
+// RUN: %clang_cc1 %s -emit-llvm -triple aarch64-unknown-unknown -o - | 
FileCheck %s --check-prefix=AARCH64
+// REQUIRES: aarch64-registered-target
+

peterwaller-arm wrote:
> aaron.ballman wrote:
> > There's nothing AArch64-specific about the change, so I'd expect some more 
> > general codegen tests.
> > 
> > Actually, I took a look to see what calls 
> > `getFloatingTypeOfSizeWithinDomain()` and I can't find any callers of that. 
> > Do you have a test case where you were hitting that particular unreachable?
> Thanks for your observation @aaron.ballman.
> 
> It appears this has been working since D105331, which enabled it for X86.
> 
> Unless I'm missing something, the function in question appears to have been 
> unused since 2010 (the last use was removed in 
> d005ac937e4c08e0c607ddc42708f8bf2064c243 by @rjmccall), I presume 
> `getFloatingTypeOfSizeWithinDomain` should be removed then.
> I presume getFloatingTypeOfSizeWithinDomain should be removed then.

Agreed; I've gone ahead and removed it in 
841355c1e4e35fc02b5b171419979f5f9af0ebc8.

I think this patch can be abandoned, unless you think the extra test coverage 
is worth adding as an NFC commit?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119926

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


[PATCH] D120397: [C++20] [Modules] Make the linkage consistent for template and its specialization

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

Linkage stuff is where I get lost quickly, hopefully @urnathan can comment 
here.  Codewise I think this looks right.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120397

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


[clang] b1a8dcf - Silence some "not all control paths return a value" warnings; NFC

2022-02-23 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-02-23T09:18:56-05:00
New Revision: b1a8dcf8c186ddfeeb062ab8475fe30365557955

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

LOG: Silence some "not all control paths return a value" warnings; NFC

Added: 


Modified: 
clang/lib/Frontend/FrontendActions.cpp
clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp

Removed: 




diff  --git a/clang/lib/Frontend/FrontendActions.cpp 
b/clang/lib/Frontend/FrontendActions.cpp
index baf3ac34db620..65cbc946179f5 100644
--- a/clang/lib/Frontend/FrontendActions.cpp
+++ b/clang/lib/Frontend/FrontendActions.cpp
@@ -823,6 +823,7 @@ static StringRef ModuleKindName(Module::ModuleKind MK) {
   case Module::PrivateModuleFragment:
 return "Private Module Fragment";
   }
+  llvm_unreachable("unknown module kind!");
 }
 
 void DumpModuleInfoAction::ExecuteAction() {

diff  --git a/clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp 
b/clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
index 2ecb9b1cd2ce2..4a817a527f2fa 100644
--- a/clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
+++ b/clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
@@ -31,6 +31,7 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const 
LRTable::Action &A) {
   case LRTable::Action::Sentinel:
 llvm_unreachable("unexpected Sentinel action kind!");
   }
+  llvm_unreachable("unexpected action kind!");
 }
 
 std::string LRTable::dumpStatistics() const {



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


[PATCH] D120334: [NFC][Lexer] Make Lexer::LangOpts const reference

2022-02-23 Thread Dawid Jurczak via Phabricator via cfe-commits
yurai007 updated this revision to Diff 410801.
yurai007 retitled this revision from "[NFC][Lexer] Use more appropriate 
LangOptionsBase type for Lexer::LangOpts" to "[NFC][Lexer] Make Lexer::LangOpts 
const reference".
yurai007 edited the summary of this revision.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120334

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


Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -136,7 +136,8 @@
  Preprocessor &PP, bool IsFirstIncludeOfFile)
 : PreprocessorLexer(&PP, FID),
   FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
-  LangOpts(PP.getLangOpts()), IsFirstTimeLexingFile(IsFirstIncludeOfFile) {
+  LangOpts(PP.getLangOpts()), LineComment(LangOpts.LineComment),
+  IsFirstTimeLexingFile(IsFirstIncludeOfFile) {
   InitLexer(InputFile.getBufferStart(), InputFile.getBufferStart(),
 InputFile.getBufferEnd());
 
@@ -149,7 +150,7 @@
 Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
  const char *BufStart, const char *BufPtr, const char *BufEnd,
  bool IsFirstIncludeOfFile)
-: FileLoc(fileloc), LangOpts(langOpts),
+: FileLoc(fileloc), LangOpts(langOpts), LineComment(LangOpts.LineComment),
   IsFirstTimeLexingFile(IsFirstIncludeOfFile) {
   InitLexer(BufStart, BufPtr, BufEnd);
 
@@ -2376,13 +2377,13 @@
 bool &TokAtPhysicalStartOfLine) {
   // If Line comments aren't explicitly enabled for this language, emit an
   // extension warning.
-  if (!LangOpts.LineComment) {
+  if (!LineComment) {
 if (!isLexingRawMode()) // There's no PP in raw mode, so can't emit diags.
   Diag(BufferPtr, diag::ext_line_comment);
 
 // Mark them enabled so we only emit one warning for this translation
 // unit.
-LangOpts.LineComment = true;
+LineComment = true;
   }
 
   // Scan over the body of the comment.  The common case, when scanning, is 
that
@@ -3433,8 +3434,7 @@
 // If the next token is obviously a // or /* */ comment, skip it 
efficiently
 // too (without going through the big switch stmt).
 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
-LangOpts.LineComment &&
-(LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
+LineComment && (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
   if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
 return true; // There is a token to return.
   goto SkipIgnoredUnits;
@@ -3741,8 +3741,8 @@
   // "foo".  Check to see if the character after the second slash is a '*'.
   // If so, we will lex that as a "/" instead of the start of a comment.
   // However, we never do this if we are just preprocessing.
-  bool TreatAsComment = LangOpts.LineComment &&
-(LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
+  bool TreatAsComment =
+  LineComment && (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
   if (!TreatAsComment)
 if (!(PP && PP->isPreprocessedOutput()))
   TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
Index: clang/include/clang/Lex/Lexer.h
===
--- clang/include/clang/Lex/Lexer.h
+++ clang/include/clang/Lex/Lexer.h
@@ -13,7 +13,6 @@
 #ifndef LLVM_CLANG_LEX_LEXER_H
 #define LLVM_CLANG_LEX_LEXER_H
 
-#include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/PreprocessorLexer.h"
@@ -36,6 +35,7 @@
 class DiagnosticBuilder;
 class Preprocessor;
 class SourceManager;
+class LangOptions;
 
 /// ConflictMarkerKind - Kinds of conflict marker which the lexer might be
 /// recovering from.
@@ -90,8 +90,11 @@
   // Location for start of file.
   SourceLocation FileLoc;
 
-  // LangOpts enabled by this language (cache).
-  LangOptions LangOpts;
+  // LangOpts enabled by this language.
+  const LangOptions &LangOpts;
+
+  // True if '//' line comments are enabled.
+  bool LineComment;
 
   // True if lexer for _Pragma handling.
   bool Is_PragmaLexer;


Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -136,7 +136,8 @@
  Preprocessor &PP, bool IsFirstIncludeOfFile)
 : PreprocessorLexer(&PP, FID),
   FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
-  LangOpts(PP.getLangOpts()), IsFirstTimeLexingFile(IsFirstIncludeOfFile) {
+  LangOpts(PP.getLangOpts()), LineComment(LangOpts.LineComment),
+  IsFirstTimeLexingFile(IsFirstIncludeOfFile) {
   InitLexer(InputFile.getBufferStart(), InputFile.getBufferStart(),
 InputFile.getBufferEnd(

[PATCH] D120262: [OpenCL] Handle TypeExtensions in OpenCLBuiltinFileEmitter

2022-02-23 Thread Pedro Ferreira via Phabricator via cfe-commits
arkangath added inline comments.



Comment at: clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp:296-298
 
+  // Emit an #if guard for all type extensions required for the given type
+  // strings.

Shouldn't what the return value means be documented here?



Comment at: clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp:1190-1191
+}
+OS << "\n";
+OptionalEndif = "#endif // TypeExtension\n";
+  }

Seems to me that this is the only assignment to the OptionalEndif variable. In 
which case, can't it be a StringRef ? And the return of the function be 
StringRef too ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120262

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


[PATCH] D120334: [NFC][Lexer] Make Lexer::LangOpts const reference

2022-02-23 Thread Dawid Jurczak via Phabricator via cfe-commits
yurai007 added a comment.

Use simpler approach with const LangOptions reference + rebase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120334

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


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

2022-02-23 Thread Dawid Jurczak via Phabricator via cfe-commits
yurai007 updated this revision to Diff 410802.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120404

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

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

[PATCH] D119290: [Clang] Add support for -fcx-limited-range, -fcx-fortran-rules options.

2022-02-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: jansvoboda11, aaron.ballman, erichkeane.
aaron.ballman added a comment.

Adding some reviewers, but the changes here look reasonable to me. You should 
fix the clang-format issues, though.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119290

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


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

2022-02-23 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam updated this revision to Diff 410803.

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

https://reviews.llvm.org/D109239

Files:
  clang/docs/LanguageExtensions.rst
  clang/docs/UsersManual.rst
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Basic/FPOptions.def
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Basic/TargetInfo.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Basic/Targets/OSTargets.h
  clang/lib/Basic/Targets/X86.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Lex/PPMacroExpansion.cpp
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CodeGen/X86/32bit-behavior-no-eval.c
  clang/test/CodeGen/X86/32bit-behavior.c
  clang/test/CodeGen/X86/fp-eval-method.c
  clang/test/CodeGen/flt_eval_macro.cpp
  clang/test/CodeGen/fp-floatcontrol-pragma.cpp
  clang/test/Preprocessor/flt_eval_macro.cpp
  clang/test/Preprocessor/init-aarch64.c
  clang/test/Preprocessor/init-arm.c
  clang/test/Preprocessor/init-mips.c
  clang/test/Preprocessor/init-ppc.c
  clang/test/Preprocessor/init-ppc64.c
  clang/test/Preprocessor/init-s390x.c
  clang/test/Preprocessor/init-v7k-compat.c
  clang/test/Preprocessor/init-x86.c
  clang/test/Preprocessor/init.c
  clang/test/Sema/fp-eval-pragma.cpp
  clang/test/Sema/x86-eval-method.c
  clang/test/Sema/x86_64-eval-method.c

Index: clang/test/Sema/x86_64-eval-method.c
===
--- /dev/null
+++ clang/test/Sema/x86_64-eval-method.c
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu -target-feature -sse -emit-llvm \
+// RUN: -o - -verify=warn %s
+//
+// RUN: %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu -emit-llvm -o - -verify=no-warn %s
+
+// no-warn-no-diagnostics
+
+float add2(float a, float b, float c) {
+#pragma clang fp eval_method(source)
+  return a + b + c;
+} // warn-warning{{Setting the floating point evaluation method to `source` on a target without SSE is not supported.}}
Index: clang/test/Sema/x86-eval-method.c
===
--- /dev/null
+++ clang/test/Sema/x86-eval-method.c
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple i386-pc-windows -target-cpu pentium4 -target-feature -sse \
+// RUN: -emit-llvm -ffp-eval-method=source  -o - -verify=warn %s
+//
+// RUN: %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple i386-pc-windows -target-cpu pentium4 \
+// RUN: -emit-llvm -ffp-eval-method=source  -o - -verify=no-warn %s
+
+// no-warn-no-diagnostics
+
+float add1(float a, float b, float c) {
+  return a + b + c;
+} // warn-warning{{Setting the floating point evaluation method to `source` on a target without SSE is not supported.}}
+
+float add2(float a, float b, float c) {
+#pragma clang fp eval_method(source)
+  return a + b + c;
+} // warn-warning{{Setting the floating point evaluation method to `source` on a target without SSE is not supported.}}
Index: clang/test/Sema/fp-eval-pragma.cpp
===
--- /dev/null
+++ clang/test/Sema/fp-eval-pragma.cpp
@@ -0,0 +1,87 @@
+// RUN: %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu -emit-llvm -o - -verify %s
+//
+// RUN: %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu -emit-llvm -o - -verify %s \
+// RUN: -ffp-eval-method=source
+//
+// RUN: %clang_cc1 -fexperimental-strict-floating-point \
+// RUN: -triple x86_64-linux-gnu -emit-llvm -o - -verify %s \
+// RUN: -ffp-eval-method=double
+
+extern "C" int printf(const char *, ...);
+
+void foo1() {
+  printf("FP: %d\n", __FLT_EVAL_METHOD__);
+}
+
+void apply_pragma() {
+  // expected-note@+1{{#pragma entered here}}
+#pragma clang fp eval_method(double)
+  // expected-error@+1{{'__FLT_EVAL_METHOD__' cannot be expanded inside a scope containing '#pragma clang fp eval_method'}}
+  printf("FP: %d\n", __FLT_EVAL_METHOD__);
+}
+
+int foo2() {
+  apply_pragma();
+  return 0;
+}
+
+void foo() {
+  auto a = __FLT_EVAL_METHOD__;
+  {
+// expected-note@+1{{#pragma entered here}}
+#pragma clang fp eval_method(double)
+// expected-error@+1{{'__FLT_EVAL_METHOD__' cannot be expanded inside a scope containing '#pragma clang fp eval_method'}}
+auto b = __FLT_EVAL_METHOD__;
+  }
+  auto c = __FLT_EVAL_METHOD__;
+}
+
+void func() {
+  {
+{
+#pragma clang fp eval_method(source)
+}
+int i = __FLT_EVAL_METHOD__; // ok, not in a scope changed by the pragma
+  }
+  {
+// expected-note@+1{{#pragma 

[PATCH] D119290: [Clang] Add support for -fcx-limited-range, -fcx-fortran-rules options.

2022-02-23 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a subscriber: mdtoguchi.
erichkeane added a comment.

Same, other than the clang-format, I see nothing to be concerned about.  
@mdtoguchi is my driver expert however.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119290

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


[PATCH] D120408: clang-format.el: Make clang-format work in indirect buffers.

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

Makes sense, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120408

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


[PATCH] D119271: CGCall: also emit LLVM `allocalign` attribute when handling AllocAlign

2022-02-23 Thread James Y Knight via Phabricator via cfe-commits
jyknight added inline comments.



Comment at: clang/lib/CodeGen/CGCall.cpp:4605
+  TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
+llvm::AttributeList NewAttrs = Attrs;
+if (AA)

durin42 wrote:
> jyknight wrote:
> > We do need to fallback to an assume for 
> > "if(CGF.SanOpts.has(SanitizerKind::Alignment)" however -- and NOT emit an 
> > allocalign (nor an align) attribute in that case.
> > 
> > This is necessary so that clang can emit explicit misalignment checks FIRST 
> > (and abort with a message if they fail), before letting LLVM assume the 
> > specified alignment. In order for the ubsan alignment check to work 
> > properly, we need to not trigger misalignment-UB before the check executes! 
> > 
> > See 
> > clang/test/CodeGen/catch-alignment-assumption-attribute-assume_aligned-on-function.cpp
> >  -- note how in the sanitized mode, it doesn't have an the "align 128" on 
> > the call result, but instead emits a bunch of code to test alignment, and 
> > branch to an ubsan abort on failure -- followed by the llvm.assume only on 
> > the successful branch. Although the test-case is only testing 
> > assume_aligned, the same behavior should be applicable to allocalign.
> > 
> > (Which shows that we clearly need a sanitized allocalign test-case, too)
> It sounds like (between this comment and the one below) I should just abandon 
> the code-sharing between AllocAlignAttrEmitter and AssumeAlignedAttrEmitter - 
> is that right?
> 
> Also, should I be making a new test case or adding to an existing one for a 
> sanitized allocalign test case? Is that an llvm-level thing or a clang-level 
> thing?
Agree, it does sound like there's not going to be much code-sharing, since 
emitAlignmentAssumption is already separate. If you find it's clearer to make 
them be separate, that sounds reasonable.

Yes, there should be a test-case for sanitized allocalign, just like for 
sanitized assume_align. 
This sanitizer is all in the frontend, see 
clang/test/CodeGen/catch-alignment-assumption-attribute-assume_aligned-on-function.cpp



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119271

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


[PATCH] D119291: [Clang] Add support for STDC CX_LIMITED_RANGE pragma.

2022-02-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: aaron.ballman, rjmccall, tahonermann, erichkeane.
aaron.ballman added a comment.

Adding some more reviewers for visibility.

Please address the clang-format issues; also, this seems to be missing all of 
the test I would expect to see in Preprocessor or Parser for checking that the 
proper diagnostics are emitted or CodeGen tests for more complicated 
situations, like:

  _Complex float range_scoped(_Complex float a, _Complex float b) {
  // CHECK-COMMON: @range_scoped
  // CHECK-COMMON: call{{.*}}complex.fmul{{.*}} #[[FULL]]
  // CHECK-COMMON: call{{.*}}complex.fdiv{{.*}} #[[FULL]]
  #pragma STDC CX_LIMITED_RANGE OFF
_Complex float res = a * b;
{
  #pragma STDC CX_LIMITED_RANGE DEFAULT
  res += a / b;
  #pragma STDC CX_LIMITED_RANGE OFF
  res += a / b;
}
return res;
  }

What should the behavior be if this pragma is at file scope instead of block 
scope (should that be diagnosed)?

(Also, this functionality should get a release note and potentially some public 
documentation?)




Comment at: clang/lib/Lex/Pragma.cpp:1028
 Diag(Tok, diag::ext_pragma_syntax_eod);
+DiscardUntilEndOfDirective();
+  }

Good catch, but do we have a test case for this change?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119291

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


[PATCH] D117611: [Sema] Warn about printf %n on Android and Fuchsia

2022-02-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D117611#3339137 , @glandium wrote:

> This doesn't leave much room to use `__attribute__((format(printf)))` on 
> custom printf implementations that do support `%n` on Android does it?

+1 to this point; whether this is or is not supported depends on which libc the 
user is linking against.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117611

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


[PATCH] D119063: [SemaCXX] Properly scope ArgumentPackSubstitutionIndex when expanding base types

2022-02-23 Thread Michael Colavita via Phabricator via cfe-commits
colavitam added a comment.

Yes, in my opinion the original shadow was accidental—you can see that every 
usage of BaseTypeLoc is immediately preceded by an initialization, though 
sometimes in a more nested scope. When initialized in the parameter pack loop, 
we skip to the next iteration of the outer loop instead of accessing it in the 
non-parameter pack path.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119063

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


[clang] 80a6968 - [clang][deps] NFC: Update documentation

2022-02-23 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-02-23T15:46:20+01:00
New Revision: 80a696898cd57f00297e06714bd5118ce7308f3e

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

LOG: [clang][deps] NFC: Update documentation

In D113473, the dependency scanner stopped emitting "-fmodule-map-file=" 
arguments. Potential build systems are expected to not add any such arguments 
on their own. This commit removes mentions of such arguments to avoid confusion.

Added: 


Modified: 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
index 2eb7a35b27b91..54c3c9543dedd 100644
--- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
+++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
@@ -16,9 +16,9 @@
 #include "llvm/ADT/StringSet.h"
 #include 
 
-namespace clang{
-namespace tooling{
-namespace dependencies{
+namespace clang {
+namespace tooling {
+namespace dependencies {
 
 /// The full dependencies and module graph for a specific input.
 struct FullDependencies {
@@ -51,15 +51,13 @@ struct FullDependencies {
   ///  be located.
   /// \param LookupModuleDeps This function is called to collect the full
   /// transitive set of dependencies for this
-  /// compilation and fill in "-fmodule-map-file="
-  /// arguments.
+  /// compilation.
   std::vector getAdditionalArgs(
   std::function LookupPCMPath,
   std::function LookupModuleDeps) const;
 
   /// Get additional arguments suitable for appending to the original Clang
-  /// command line, excluding arguments containing modules-related paths:
-  /// "-fmodule-file=", "-fmodule-map-file=".
+  /// command line, excluding "-fmodule-file=" arguments.
   std::vector getAdditionalArgsWithoutModulePaths() const;
 };
 

diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h 
b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
index d1a7aab8c24b1..c2e9541db68e0 100644
--- a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
+++ b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
@@ -111,15 +111,13 @@ struct ModuleDeps {
   ///  be located.
   /// \param LookupModuleDeps This function is called to collect the full
   /// transitive set of dependencies for this
-  /// compilation and fill in "-fmodule-map-file="
-  /// arguments.
+  /// compilation.
   std::vector getCanonicalCommandLine(
   std::function LookupPCMPath,
   std::function LookupModuleDeps) const;
 
   /// Gets the canonical command line suitable for passing to clang, excluding
-  /// arguments containing modules-related paths: "-fmodule-file=", "-o",
-  /// "-fmodule-map-file=".
+  /// "-fmodule-file=" and "-o" arguments.
   std::vector getCanonicalCommandLineWithoutModulePaths() const;
 };
 

diff  --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
index 739712baadd06..26f91961c2bbd 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
@@ -9,9 +9,9 @@
 #include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
 #include "clang/Frontend/Utils.h"
 
-namespace clang{
-namespace tooling{
-namespace dependencies{
+namespace clang {
+namespace tooling {
+namespace dependencies {
 
 std::vector FullDependencies::getAdditionalArgs(
 std::function LookupPCMPath,



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


[clang] 19017c2 - [clang][deps] Return the whole TU command line

2022-02-23 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-02-23T15:46:20+01:00
New Revision: 19017c2435d76fe453a2500eeafd045ba92ece67

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

LOG: [clang][deps] Return the whole TU command line

The dependency scanner already generates canonical -cc1 command lines that can 
be used to compile discovered modular dependencies.

For translation unit command lines, the scanner only generates additional 
driver arguments the build system is expected to append to the original command 
line.

While this works most of the time, there are situations where that's not the 
case. For example with `-Wunused-command-line-argument`, Clang will complain 
about the `-fmodules-cache-path=` argument that's not being used in explicit 
modular builds. Combine that with `-Werror` and the build outright fails.

To prevent such failures, this patch changes the dependency scanner to return 
the full driver command line to compile the original translation unit. This 
gives us more opportunities to massage the arguments into something reasonable.

Reviewed By: Bigcheese

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

Added: 


Modified: 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
clang/test/ClangScanDeps/diagnostics.c
clang/test/ClangScanDeps/modules-context-hash.c
clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m
clang/test/ClangScanDeps/modules-full.cpp
clang/test/ClangScanDeps/modules-inferred-explicit-build.m
clang/test/ClangScanDeps/modules-inferred.m
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/modules-symlink.c
clang/tools/clang-scan-deps/ClangScanDeps.cpp

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
index 54c3c9543dedd..36447dd2e38e6 100644
--- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
+++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
@@ -42,8 +42,10 @@ struct FullDependencies {
   /// determined that the 
diff erences are benign for this compilation.
   std::vector ClangModuleDeps;
 
-  /// Get additional arguments suitable for appending to the original Clang
-  /// command line.
+  /// The original command line of the TU (excluding the compiler executable).
+  std::vector OriginalCommandLine;
+
+  /// Get the full command line.
   ///
   /// \param LookupPCMPath This function is called to fill in "-fmodule-file="
   ///  arguments and the "-o" argument. It needs to return
@@ -52,10 +54,13 @@ struct FullDependencies {
   /// \param LookupModuleDeps This function is called to collect the full
   /// transitive set of dependencies for this
   /// compilation.
-  std::vector getAdditionalArgs(
+  std::vector getCommandLine(
   std::function LookupPCMPath,
   std::function LookupModuleDeps) const;
 
+  /// Get the full command line, excluding -fmodule-file=" arguments.
+  std::vector getCommandLineWithoutModulePaths() const;
+
   /// Get additional arguments suitable for appending to the original Clang
   /// command line, excluding "-fmodule-file=" arguments.
   std::vector getAdditionalArgsWithoutModulePaths() const;

diff  --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
index 26f91961c2bbd..2723d4742819a 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
@@ -13,10 +13,10 @@ namespace clang {
 namespace tooling {
 namespace dependencies {
 
-std::vector FullDependencies::getAdditionalArgs(
+std::vector FullDependencies::getCommandLine(
 std::function LookupPCMPath,
 std::function LookupModuleDeps) const {
-  std::vector Ret = getAdditionalArgsWithoutModulePaths();
+  std::vector Ret = getCommandLineWithoutModulePaths();
 
   std::vector PCMPaths;
   std::vector ModMapPaths;
@@ -28,6 +28,19 @@ std::vector FullDependencies::getAdditionalArgs(
   return Ret;
 }
 
+std::vector
+FullDependencies::getCommandLineWithoutModulePaths() const {
+  std::vector Args = OriginalCommandLine;
+
+  std::vector AdditionalArgs =
+  getAdditionalArgsWithoutModulePaths();
+  Args.insert(Args.end(), AdditionalArgs.begin(), AdditionalArgs.end());
+
+  // TODO: Filter out implicit modules leftovers (e.g. 
"-fmodules-cache-path=").
+
+  return Args;
+}
+
 

[PATCH] D118986: [clang][deps] Return the whole TU command line

2022-02-23 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG19017c2435d7: [clang][deps] Return the whole TU command line 
(authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D118986?vs=405925&id=410806#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118986

Files:
  clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
  clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
  clang/test/ClangScanDeps/diagnostics.c
  clang/test/ClangScanDeps/modules-context-hash.c
  clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m
  clang/test/ClangScanDeps/modules-full.cpp
  clang/test/ClangScanDeps/modules-inferred-explicit-build.m
  clang/test/ClangScanDeps/modules-inferred.m
  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/modules-symlink.c
  clang/tools/clang-scan-deps/ClangScanDeps.cpp

Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -296,14 +296,13 @@
   Modules.insert(I, {{MD.ID, InputIndex}, std::move(MD)});
 }
 
-ID.AdditionalCommandLine =
-GenerateModulesPathArgs
-? FD.getAdditionalArgs(
-  [&](ModuleID MID) { return lookupPCMPath(MID); },
-  [&](ModuleID MID) -> const ModuleDeps & {
-return lookupModuleDeps(MID);
-  })
-: FD.getAdditionalArgsWithoutModulePaths();
+ID.CommandLine = GenerateModulesPathArgs
+ ? FD.getCommandLine(
+   [&](ModuleID MID) { return lookupPCMPath(MID); },
+   [&](ModuleID MID) -> const ModuleDeps & {
+ return lookupModuleDeps(MID);
+   })
+ : FD.getCommandLineWithoutModulePaths();
 
 Inputs.push_back(std::move(ID));
   }
@@ -353,7 +352,7 @@
   {"clang-context-hash", I.ContextHash},
   {"file-deps", I.FileDeps},
   {"clang-module-deps", toJSONSorted(I.ModuleDeps)},
-  {"command-line", I.AdditionalCommandLine},
+  {"command-line", I.CommandLine},
   };
   TUs.push_back(std::move(O));
 }
@@ -415,7 +414,7 @@
 std::string ContextHash;
 std::vector FileDeps;
 std::vector ModuleDeps;
-std::vector AdditionalCommandLine;
+std::vector CommandLine;
   };
 
   std::mutex Lock;
Index: clang/test/ClangScanDeps/modules-symlink.c
===
--- clang/test/ClangScanDeps/modules-symlink.c
+++ clang/test/ClangScanDeps/modules-symlink.c
@@ -49,8 +49,7 @@
 // RUN:   --tu-index=0 > %t/pch.rsp
 //
 // RUN: %clang @%t/mod.cc1.rsp
-// RUN: %clang -x c-header %t/pch.h -fmodules -gmodules -fimplicit-module-maps \
-// RUN:   -fmodules-cache-path=%t/cache -o %t/pch.h.gch -I %t @%t/pch.rsp
+// RUN: %clang @%t/pch.rsp
 
 // RUN: sed -e "s|DIR|%/t|g" %t/cdb_tu.json > %t/cdb.json
 // RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full \
Index: clang/test/ClangScanDeps/modules-pch.c
===
--- clang/test/ClangScanDeps/modules-pch.c
+++ clang/test/ClangScanDeps/modules-pch.c
@@ -91,7 +91,7 @@
 // CHECK-PCH-NEXT: }
 // CHECK-PCH-NEXT:   ],
 // CHECK-PCH-NEXT:   "command-line": [
-// CHECK-PCH-NEXT: "-fno-implicit-modules",
+// CHECK-PCH:  "-fno-implicit-modules",
 // CHECK-PCH-NEXT: "-fno-implicit-module-maps",
 // CHECK-PCH-NEXT: "-fmodule-file=[[PREFIX]]/build/[[HASH_MOD_COMMON_1]]/ModCommon1-{{.*}}.pcm",
 // CHECK-PCH-NEXT: "-fmodule-file=[[PREFIX]]/build/[[HASH_MOD_COMMON_2]]/ModCommon2-{{.*}}.pcm",
@@ -120,8 +120,7 @@
 // RUN: %clang @%t/mod_common_1.cc1.rsp
 // RUN: %clang @%t/mod_common_2.cc1.rsp
 // RUN: %clang @%t/mod_pch.cc1.rsp
-// RUN: %clang -x c-header %t/pch.h -fmodules -gmodules -fimplicit-module-maps \
-// RUN:   -fmodules-cache-path=%t/cache -o %t/pch.h.gch @%t/pch.rsp
+// RUN: %clang @%t/pch.rsp
 
 // Scan dependencies of the TU:
 //
@@ -161,7 +160,7 @@
 // CHECK-TU-NEXT: }
 // CHECK-TU-NEXT:   ],
 // CHECK-TU-NEXT:   "command-line": [
-// CHECK-TU-NEXT: "-fno-implicit-modules",
+// CHECK-TU:  "-fno-implicit-modules",
 // CHECK-TU-NEXT: "-fno-implicit-module-maps",
 // CHECK-TU-NEXT: "-fmodule-file=[[PREFIX]]/build/[[HASH_MOD_TU]]/ModTU-{{.*}}.pcm"
 // CHECK-TU-NEXT:   ],
@@ -183,8 +182,7 @@
 // RUN:   --tu-index=0 > %t/tu.rsp
 //
 // RUN: %cl

[PATCH] D120408: clang-format.el: Make clang-format work in indirect buffers.

2022-02-23 Thread Philipp via Phabricator via cfe-commits
phst added a comment.

Thanks for the review! I think you have to commit this (I don't have commit 
access).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120408

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


  1   2   3   >