[clang] [clang-repl] Extend the C support. (PR #89804)

2024-05-22 Thread Jun Zhang via cfe-commits

junaire wrote:

Just found out this keeps popping up from my notification, and I would like 
give my 2 cents, maybe can provide some insights:

Looking at the backtrace of the failing tests, I noticed we ran into 
`clang::Parser::ParseTopLevelStmtDecl()` which makes me very confused. Do we 
actually enable the incremental extension in lldb? I grep it in lldb codebase 
and the only occurrence is here 
https://github.com/llvm/llvm-project/blob/b91b8fea8c58e9b414e291df677b12ca44197784/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp#L662

The other thing I noticed is that the failure looks like have something to do 
with the objc, can we also check the current language we're compiling when 
skipping removing the name for the lexical scope?

https://github.com/llvm/llvm-project/pull/89804
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-repl] Add call to 'InitializeAllAsmParsers' (PR #86727)

2024-04-02 Thread Jun Zhang via cfe-commits

junaire wrote:

> @weliveindetail @vgvassilev @junaire: sorry for pinging you directly, but 
> could you take a look at this PR? I see you're all active on other 
> `clang-repl` PRs, so thought you might be the best place to start to take a 
> look at this one 爛

Hi, thanks for the PR. I think the change looks reasonable but I'm no longer 
working on this so I've picked some reviewers for you. They should be able to 
look at this soon.

https://github.com/llvm/llvm-project/pull/86727
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-repl] Fix BUILD_SHARED_LIBS symbols from libclangInterpreter on MinGW (PR #71393)

2023-11-06 Thread Jun Zhang via cfe-commits

https://github.com/junaire approved this pull request.

Thanks for the fix! I'm fine with it if this fixes your problem. But yeah, 
please make sure @vgvassilev is aware of it.

https://github.com/llvm/llvm-project/pull/71393
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Add Documentation for Execution Results Handling in Clang-Repl (PR #65650)

2023-10-13 Thread Jun Zhang via cfe-commits


@@ -213,6 +213,411 @@ concept helps support advanced use cases such as template 
instantiations on dema
 automatic language interoperability. It also helps static languages such as 
C/C++ become
 apt for data science.
 
+Execution Results Handling in Clang-Repl
+
+
+Execution Results Handling features discussed below help extend the Clang-Repl
+functionality by creating an interface between the execution results of a
+program and the compiled program.
+
+1. **Capture Execution Results**: This feature helps capture the execution 
results
+of a program and bring them back to the compiled program.
+
+2. **Dump Captured Execution Results**: This feature helps create a temporary 
dump
+for Value Printing/Automatic Printf, that is, to display the value and type of
+the captured data.
+
+
+1. Capture Execution Results
+
+
+In many cases, it is useful to bring back the program execution result to the
+compiled program. This result can be stored in an object of type **Value**.
+
+How Execution Results are captured (Value Synthesis):
+-
+
+The synthesizer chooses which expression to synthesize, and then it replaces
+the original expression with the synthesized expression. Depending on the
+expression type, it may choose to save an object (``LastValue``) of type 
'value'
+while allocating memory to it (``SetValueWithAlloc()``), or not (
+``SetValueNoAlloc()``).
+
+.. graphviz::
+:name: valuesynthesis
+:caption: Value Synthesis
+:alt: Shows how an object of type 'Value' is synthesized
+:align: center
+
+ digraph "valuesynthesis" {
+ rankdir="LR";
+ graph [fontname="Verdana", fontsize="12"];
+ node [fontname="Verdana", fontsize="12"];
+ edge [fontname="Sans", fontsize="9"];
+
+ start [label=" Create an Object \n 'Last Value' \n of type 'Value' ", 
shape="note", fontcolor=white, fillcolor="#ff", style=filled];
+ assign [label=" Assign the result \n to the 'LastValue' \n (based on 
respective \n Memory Allocation \n scenario) ", shape="box"]
+ print [label=" Pretty Print \n the Value Object ", shape="Msquare", 
fillcolor="yellow", style=filled];
+ start -> assign;
+ assign -> print;
+
+   subgraph SynthesizeExpression {
+ synth [label=" SynthesizeExpr() ", shape="note", fontcolor=white, 
fillcolor="#ff", style=filled];
+ mem [label=" New Memory \n Allocation? ", shape="diamond"];
+ withaloc [label=" SetValueWithAlloc() ", shape="box"];
+ noaloc [label=" SetValueNoAlloc() ", shape="box"];
+ right [label=" 1. RValue Structure \n (a temporary value)", 
shape="box"];
+ left2 [label=" 2. LValue Structure \n (a variable with \n an 
address)", shape="box"];
+ left3 [label=" 3. Built-In Type \n (int, float, etc.)", 
shape="box"];
+ output [label=" move to 'Assign' step ", shape="box"];
+
+ synth -> mem;
+ mem -> withaloc [label="Yes"];
+ mem -> noaloc [label="No"];
+ withaloc -> right;
+ noaloc -> left2;
+ noaloc -> left3;
+ right -> output;
+ left2 -> output;
+ left3 -> output;
+  }
+output -> assign
+  }
+
+Where is the captured result stored?
+
+
+``LastValue`` holds the last result of the value printing. It is a class member
+because it can be accessed even after subsequent inputs.
+
+**Note:** If no value printing happens, then it is in an invalid state.
+
+Improving Efficiency and User Experience
+
+
+The Value object is essentially used to create a mapping between an expression
+'type' and the allocated 'memory'. Built-in types (bool, char, int,
+float, double, etc.) are copyable. Their memory allocation size is known
+and the Value object can introduce a small-buffer optimization.
+In case of objects, the ``Value`` class provides reference-counted memory
+management.
+
+The implementation maps the type as written and the Clang Type to be able to 
use
+the preprocessor to synthesize the relevant cast operations. For example,
+``X(char, Char_S)``, where ``char`` is the type from the language's type system
+and ``Char_S`` is the Clang builtin type which represents it. This mapping 
helps
+to import execution results from the interpreter in a compiled program and vice
+versa. The ``Value.h`` header file can be included at runtime and this is why 
it
+has a very low token count and was developed with strict constraints in mind.
+
+This also enables the user to receive the computed 'type' back in their code
+and then transform the type into something else (e.g., re-cast a double into
+a float). Normally, the compiler can handle these conversions transparently,
+but in interpreter mode, the 

[clang] 5111286 - Reland "Reland [clang-repl] Introduce Value to capture expression results"

2023-05-23 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2023-05-23T19:32:31+08:00
New Revision: 5111286f06e1e10f24745007a45a830760f1790c

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

LOG: Reland "Reland [clang-repl] Introduce Value to capture expression results"

This reverts commit 094ab4781262b6cb49d57b0ecdf84b047c879295.

Reland with changing `ParseAndExecute` to `Parse` in
`Interpreter::create`. This avoid creating JIT instance everytime even
if we don't really need them.

This should fixes failures like 
https://lab.llvm.org/buildbot/#/builders/38/builds/11955

The original reverted patch also causes GN bot fails on M1. 
(https://lab.llvm.org/buildbot/#/builders/38/builds/11955)
However, we can't reproduce it so let's reland it and see what happens.
See discussions here: 
https://reviews.llvm.org/rGd71a4e02277a64a9dece591cdf2b34f15c3b19a0

Added: 
clang/include/clang/Interpreter/Value.h
clang/lib/Interpreter/InterpreterUtils.cpp
clang/lib/Interpreter/InterpreterUtils.h
clang/lib/Interpreter/Value.cpp

Modified: 
clang/include/clang/Interpreter/Interpreter.h
clang/lib/Interpreter/CMakeLists.txt
clang/lib/Interpreter/IncrementalParser.cpp
clang/lib/Interpreter/IncrementalParser.h
clang/lib/Interpreter/Interpreter.cpp
clang/tools/clang-repl/CMakeLists.txt
clang/unittests/Interpreter/CMakeLists.txt
clang/unittests/Interpreter/InterpreterTest.cpp

Removed: 




diff  --git a/clang/include/clang/Interpreter/Interpreter.h 
b/clang/include/clang/Interpreter/Interpreter.h
index b3d64458d777c..e680218452d1c 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -14,14 +14,15 @@
 #ifndef LLVM_CLANG_INTERPRETER_INTERPRETER_H
 #define LLVM_CLANG_INTERPRETER_INTERPRETER_H
 
-#include "clang/Interpreter/PartialTranslationUnit.h"
-
+#include "clang/AST/Decl.h"
 #include "clang/AST/GlobalDecl.h"
+#include "clang/Interpreter/PartialTranslationUnit.h"
+#include "clang/Interpreter/Value.h"
 
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ExecutionEngine/JITSymbol.h"
 #include "llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h"
 #include "llvm/Support/Error.h"
-
 #include 
 #include 
 
@@ -54,24 +55,26 @@ class Interpreter {
   Interpreter(std::unique_ptr CI, llvm::Error );
 
   llvm::Error CreateExecutor();
+  unsigned InitPTUSize = 0;
+
+  // This member holds the last result of the value printing. It's a class
+  // member because we might want to access it after more inputs. If no value
+  // printing happens, it's in an invalid state.
+  Value LastValue;
 
 public:
   ~Interpreter();
   static llvm::Expected>
   create(std::unique_ptr CI);
+  const ASTContext () const;
+  ASTContext ();
   const CompilerInstance *getCompilerInstance() const;
   llvm::Expected getExecutionEngine();
 
   llvm::Expected Parse(llvm::StringRef Code);
   llvm::Error Execute(PartialTranslationUnit );
-  llvm::Error ParseAndExecute(llvm::StringRef Code) {
-auto PTU = Parse(Code);
-if (!PTU)
-  return PTU.takeError();
-if (PTU->TheModule)
-  return Execute(*PTU);
-return llvm::Error::success();
-  }
+  llvm::Error ParseAndExecute(llvm::StringRef Code, Value *V = nullptr);
+  llvm::Expected CompileDtorCall(CXXRecordDecl 
*CXXRD);
 
   /// Undo N previous incremental inputs.
   llvm::Error Undo(unsigned N = 1);
@@ -92,6 +95,23 @@ class Interpreter {
   /// file.
   llvm::Expected
   getSymbolAddressFromLinkerName(llvm::StringRef LinkerName) const;
+
+  enum InterfaceKind { NoAlloc, WithAlloc, CopyArray };
+
+  const llvm::SmallVectorImpl () const {
+return ValuePrintingInfo;
+  }
+
+  Expr *SynthesizeExpr(Expr *E);
+
+private:
+  size_t getEffectivePTUSize() const;
+
+  bool FindRuntimeInterface();
+
+  llvm::DenseMap Dtors;
+
+  llvm::SmallVector ValuePrintingInfo;
 };
 } // namespace clang
 

diff  --git a/clang/include/clang/Interpreter/Value.h 
b/clang/include/clang/Interpreter/Value.h
new file mode 100644
index 0..4df4367030ecd
--- /dev/null
+++ b/clang/include/clang/Interpreter/Value.h
@@ -0,0 +1,202 @@
+//===--- Value.h - Definition of interpreter value --*- 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
+//
+//===--===//
+//
+// Value is a lightweight struct that is used for carrying execution results in
+// clang-repl. It's a special runtime that acts like a messager between 
compiled
+// code and interpreted code. This makes it possible to exchange interesting
+// information between the compiled & interpreted world.
+//
+// A typical usage is 

[clang] 094ab47 - Revert "Reland [clang-repl] Introduce Value to capture expression results"

2023-05-19 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2023-05-19T20:56:21+08:00
New Revision: 094ab4781262b6cb49d57b0ecdf84b047c879295

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

LOG: Revert "Reland [clang-repl] Introduce Value to capture expression results"

This reverts commit d71a4e02277a64a9dece591cdf2b34f15c3b19a0.
See http://45.33.8.238/macm1/61024/step_7.txt

Added: 


Modified: 
clang/include/clang/Interpreter/Interpreter.h
clang/lib/Interpreter/CMakeLists.txt
clang/lib/Interpreter/IncrementalParser.cpp
clang/lib/Interpreter/IncrementalParser.h
clang/lib/Interpreter/Interpreter.cpp
clang/tools/clang-repl/CMakeLists.txt
clang/unittests/Interpreter/CMakeLists.txt
clang/unittests/Interpreter/InterpreterTest.cpp

Removed: 
clang/include/clang/Interpreter/Value.h
clang/lib/Interpreter/InterpreterUtils.cpp
clang/lib/Interpreter/InterpreterUtils.h
clang/lib/Interpreter/Value.cpp



diff  --git a/clang/include/clang/Interpreter/Interpreter.h 
b/clang/include/clang/Interpreter/Interpreter.h
index e680218452d1c..b3d64458d777c 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -14,15 +14,14 @@
 #ifndef LLVM_CLANG_INTERPRETER_INTERPRETER_H
 #define LLVM_CLANG_INTERPRETER_INTERPRETER_H
 
-#include "clang/AST/Decl.h"
-#include "clang/AST/GlobalDecl.h"
 #include "clang/Interpreter/PartialTranslationUnit.h"
-#include "clang/Interpreter/Value.h"
 
-#include "llvm/ADT/DenseMap.h"
+#include "clang/AST/GlobalDecl.h"
+
 #include "llvm/ExecutionEngine/JITSymbol.h"
 #include "llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h"
 #include "llvm/Support/Error.h"
+
 #include 
 #include 
 
@@ -55,26 +54,24 @@ class Interpreter {
   Interpreter(std::unique_ptr CI, llvm::Error );
 
   llvm::Error CreateExecutor();
-  unsigned InitPTUSize = 0;
-
-  // This member holds the last result of the value printing. It's a class
-  // member because we might want to access it after more inputs. If no value
-  // printing happens, it's in an invalid state.
-  Value LastValue;
 
 public:
   ~Interpreter();
   static llvm::Expected>
   create(std::unique_ptr CI);
-  const ASTContext () const;
-  ASTContext ();
   const CompilerInstance *getCompilerInstance() const;
   llvm::Expected getExecutionEngine();
 
   llvm::Expected Parse(llvm::StringRef Code);
   llvm::Error Execute(PartialTranslationUnit );
-  llvm::Error ParseAndExecute(llvm::StringRef Code, Value *V = nullptr);
-  llvm::Expected CompileDtorCall(CXXRecordDecl 
*CXXRD);
+  llvm::Error ParseAndExecute(llvm::StringRef Code) {
+auto PTU = Parse(Code);
+if (!PTU)
+  return PTU.takeError();
+if (PTU->TheModule)
+  return Execute(*PTU);
+return llvm::Error::success();
+  }
 
   /// Undo N previous incremental inputs.
   llvm::Error Undo(unsigned N = 1);
@@ -95,23 +92,6 @@ class Interpreter {
   /// file.
   llvm::Expected
   getSymbolAddressFromLinkerName(llvm::StringRef LinkerName) const;
-
-  enum InterfaceKind { NoAlloc, WithAlloc, CopyArray };
-
-  const llvm::SmallVectorImpl () const {
-return ValuePrintingInfo;
-  }
-
-  Expr *SynthesizeExpr(Expr *E);
-
-private:
-  size_t getEffectivePTUSize() const;
-
-  bool FindRuntimeInterface();
-
-  llvm::DenseMap Dtors;
-
-  llvm::SmallVector ValuePrintingInfo;
 };
 } // namespace clang
 

diff  --git a/clang/include/clang/Interpreter/Value.h 
b/clang/include/clang/Interpreter/Value.h
deleted file mode 100644
index 4df4367030ecd..0
--- a/clang/include/clang/Interpreter/Value.h
+++ /dev/null
@@ -1,202 +0,0 @@
-//===--- Value.h - Definition of interpreter value --*- 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
-//
-//===--===//
-//
-// Value is a lightweight struct that is used for carrying execution results in
-// clang-repl. It's a special runtime that acts like a messager between 
compiled
-// code and interpreted code. This makes it possible to exchange interesting
-// information between the compiled & interpreted world.
-//
-// A typical usage is like the below:
-//
-// Value V;
-// Interp.ParseAndExecute("int x = 42;");
-// Interp.ParseAndExecute("x", );
-// V.getType(); // <-- Yields a clang::QualType.
-// V.getInt(); // <-- Yields 42.
-//
-// The current design is still highly experimental and nobody should rely on 
the
-// API being stable because we're hopefully going to make significant changes 
to
-// it in the relatively near future. For example, Value also intends to be used
-// as an exchange token for JIT support enabling 

[clang] d71a4e0 - Reland [clang-repl] Introduce Value to capture expression results

2023-05-18 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2023-05-19T13:40:44+08:00
New Revision: d71a4e02277a64a9dece591cdf2b34f15c3b19a0

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

LOG: Reland [clang-repl] Introduce Value to capture expression results

This reverts commit 7158fd381a0bc0222195d6a07ebb42ea57957bda.
* Fixes endianness issue on big endian machines like PowerPC-bl
* Disable tests on platforms that having trouble to support JIT

Signed-off-by: Jun Zhang 

Added: 
clang/include/clang/Interpreter/Value.h
clang/lib/Interpreter/InterpreterUtils.cpp
clang/lib/Interpreter/InterpreterUtils.h
clang/lib/Interpreter/Value.cpp

Modified: 
clang/include/clang/Interpreter/Interpreter.h
clang/lib/Interpreter/CMakeLists.txt
clang/lib/Interpreter/IncrementalParser.cpp
clang/lib/Interpreter/IncrementalParser.h
clang/lib/Interpreter/Interpreter.cpp
clang/tools/clang-repl/CMakeLists.txt
clang/unittests/Interpreter/CMakeLists.txt
clang/unittests/Interpreter/InterpreterTest.cpp

Removed: 




diff  --git a/clang/include/clang/Interpreter/Interpreter.h 
b/clang/include/clang/Interpreter/Interpreter.h
index b3d64458d777c..e680218452d1c 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -14,14 +14,15 @@
 #ifndef LLVM_CLANG_INTERPRETER_INTERPRETER_H
 #define LLVM_CLANG_INTERPRETER_INTERPRETER_H
 
-#include "clang/Interpreter/PartialTranslationUnit.h"
-
+#include "clang/AST/Decl.h"
 #include "clang/AST/GlobalDecl.h"
+#include "clang/Interpreter/PartialTranslationUnit.h"
+#include "clang/Interpreter/Value.h"
 
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ExecutionEngine/JITSymbol.h"
 #include "llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h"
 #include "llvm/Support/Error.h"
-
 #include 
 #include 
 
@@ -54,24 +55,26 @@ class Interpreter {
   Interpreter(std::unique_ptr CI, llvm::Error );
 
   llvm::Error CreateExecutor();
+  unsigned InitPTUSize = 0;
+
+  // This member holds the last result of the value printing. It's a class
+  // member because we might want to access it after more inputs. If no value
+  // printing happens, it's in an invalid state.
+  Value LastValue;
 
 public:
   ~Interpreter();
   static llvm::Expected>
   create(std::unique_ptr CI);
+  const ASTContext () const;
+  ASTContext ();
   const CompilerInstance *getCompilerInstance() const;
   llvm::Expected getExecutionEngine();
 
   llvm::Expected Parse(llvm::StringRef Code);
   llvm::Error Execute(PartialTranslationUnit );
-  llvm::Error ParseAndExecute(llvm::StringRef Code) {
-auto PTU = Parse(Code);
-if (!PTU)
-  return PTU.takeError();
-if (PTU->TheModule)
-  return Execute(*PTU);
-return llvm::Error::success();
-  }
+  llvm::Error ParseAndExecute(llvm::StringRef Code, Value *V = nullptr);
+  llvm::Expected CompileDtorCall(CXXRecordDecl 
*CXXRD);
 
   /// Undo N previous incremental inputs.
   llvm::Error Undo(unsigned N = 1);
@@ -92,6 +95,23 @@ class Interpreter {
   /// file.
   llvm::Expected
   getSymbolAddressFromLinkerName(llvm::StringRef LinkerName) const;
+
+  enum InterfaceKind { NoAlloc, WithAlloc, CopyArray };
+
+  const llvm::SmallVectorImpl () const {
+return ValuePrintingInfo;
+  }
+
+  Expr *SynthesizeExpr(Expr *E);
+
+private:
+  size_t getEffectivePTUSize() const;
+
+  bool FindRuntimeInterface();
+
+  llvm::DenseMap Dtors;
+
+  llvm::SmallVector ValuePrintingInfo;
 };
 } // namespace clang
 

diff  --git a/clang/include/clang/Interpreter/Value.h 
b/clang/include/clang/Interpreter/Value.h
new file mode 100644
index 0..e75a90505154a
--- /dev/null
+++ b/clang/include/clang/Interpreter/Value.h
@@ -0,0 +1,200 @@
+//===--- Value.h - Definition of interpreter value --*- 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
+//
+//===--===//
+//
+// Value is a lightweight struct that is used for carrying execution results in
+// clang-repl. It's a special runtime that acts like a messager between 
compiled
+// code and interpreted code. This makes it possible to exchange interesting
+// information between the compiled & interpreted world.
+//
+// A typical usage is like the below:
+//
+// Value V;
+// Interp.ParseAndExecute("int x = 42;");
+// Interp.ParseAndExecute("x", );
+// V.getType(); // <-- Yields a clang::QualType.
+// V.getInt(); // <-- Yields 42.
+//
+// The current design is still highly experimental and nobody should rely on 
the
+// API being stable because we're hopefully going to make significant changes 
to
+// it in the 

[clang] 7158fd3 - Revert "[clang-repl] Introduce Value to capture expression results"

2023-05-16 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2023-05-16T21:21:52+08:00
New Revision: 7158fd381a0bc0222195d6a07ebb42ea57957bda

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

LOG: Revert "[clang-repl] Introduce Value to capture expression results"

This reverts commit a423b7f1d7ca8b263af85944f57a69aa08fc942c.
See https://lab.llvm.org/buildbot/#/changes/95083

Added: 


Modified: 
clang/include/clang/Interpreter/Interpreter.h
clang/lib/Interpreter/CMakeLists.txt
clang/lib/Interpreter/IncrementalParser.cpp
clang/lib/Interpreter/IncrementalParser.h
clang/lib/Interpreter/Interpreter.cpp
clang/tools/clang-repl/CMakeLists.txt
clang/unittests/Interpreter/CMakeLists.txt
clang/unittests/Interpreter/InterpreterTest.cpp

Removed: 
clang/include/clang/Interpreter/Value.h
clang/lib/Interpreter/InterpreterUtils.cpp
clang/lib/Interpreter/InterpreterUtils.h
clang/lib/Interpreter/Value.cpp



diff  --git a/clang/include/clang/Interpreter/Interpreter.h 
b/clang/include/clang/Interpreter/Interpreter.h
index e680218452d1c..b3d64458d777c 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -14,15 +14,14 @@
 #ifndef LLVM_CLANG_INTERPRETER_INTERPRETER_H
 #define LLVM_CLANG_INTERPRETER_INTERPRETER_H
 
-#include "clang/AST/Decl.h"
-#include "clang/AST/GlobalDecl.h"
 #include "clang/Interpreter/PartialTranslationUnit.h"
-#include "clang/Interpreter/Value.h"
 
-#include "llvm/ADT/DenseMap.h"
+#include "clang/AST/GlobalDecl.h"
+
 #include "llvm/ExecutionEngine/JITSymbol.h"
 #include "llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h"
 #include "llvm/Support/Error.h"
+
 #include 
 #include 
 
@@ -55,26 +54,24 @@ class Interpreter {
   Interpreter(std::unique_ptr CI, llvm::Error );
 
   llvm::Error CreateExecutor();
-  unsigned InitPTUSize = 0;
-
-  // This member holds the last result of the value printing. It's a class
-  // member because we might want to access it after more inputs. If no value
-  // printing happens, it's in an invalid state.
-  Value LastValue;
 
 public:
   ~Interpreter();
   static llvm::Expected>
   create(std::unique_ptr CI);
-  const ASTContext () const;
-  ASTContext ();
   const CompilerInstance *getCompilerInstance() const;
   llvm::Expected getExecutionEngine();
 
   llvm::Expected Parse(llvm::StringRef Code);
   llvm::Error Execute(PartialTranslationUnit );
-  llvm::Error ParseAndExecute(llvm::StringRef Code, Value *V = nullptr);
-  llvm::Expected CompileDtorCall(CXXRecordDecl 
*CXXRD);
+  llvm::Error ParseAndExecute(llvm::StringRef Code) {
+auto PTU = Parse(Code);
+if (!PTU)
+  return PTU.takeError();
+if (PTU->TheModule)
+  return Execute(*PTU);
+return llvm::Error::success();
+  }
 
   /// Undo N previous incremental inputs.
   llvm::Error Undo(unsigned N = 1);
@@ -95,23 +92,6 @@ class Interpreter {
   /// file.
   llvm::Expected
   getSymbolAddressFromLinkerName(llvm::StringRef LinkerName) const;
-
-  enum InterfaceKind { NoAlloc, WithAlloc, CopyArray };
-
-  const llvm::SmallVectorImpl () const {
-return ValuePrintingInfo;
-  }
-
-  Expr *SynthesizeExpr(Expr *E);
-
-private:
-  size_t getEffectivePTUSize() const;
-
-  bool FindRuntimeInterface();
-
-  llvm::DenseMap Dtors;
-
-  llvm::SmallVector ValuePrintingInfo;
 };
 } // namespace clang
 

diff  --git a/clang/include/clang/Interpreter/Value.h 
b/clang/include/clang/Interpreter/Value.h
deleted file mode 100644
index 90a0097e5cc37..0
--- a/clang/include/clang/Interpreter/Value.h
+++ /dev/null
@@ -1,200 +0,0 @@
-//===--- Value.h - Definition of interpreter value --*- 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
-//
-//===--===//
-//
-// Value is a lightweight struct that is used for carrying execution results in
-// clang-repl. It's a special runtime that acts like a messager between 
compiled
-// code and interpreted code. This makes it possible to exchange interesting
-// information between the compiled & interpreted world.
-//
-// A typical usage is like the below:
-//
-// Value V;
-// Interp.ParseAndExecute("int x = 42;");
-// Interp.ParseAndExecute("x", );
-// V.getType(); // <-- Yields a clang::QualType.
-// V.getInt(); // <-- Yields 42.
-//
-// The current design is still highly experimental and nobody should rely on 
the
-// API being stable because we're hopefully going to make significant changes 
to
-// it in the relatively near future. For example, Value also intends to be used
-// as an exchange token for JIT support enabling remote 

[clang] a423b7f - [clang-repl] Introduce Value to capture expression results

2023-05-16 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2023-05-16T20:10:49+08:00
New Revision: a423b7f1d7ca8b263af85944f57a69aa08fc942c

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

LOG: [clang-repl] Introduce Value to capture expression results

This is the second part of the below RFC:
https://discourse.llvm.org/t/rfc-handle-execution-results-in-clang-repl/68493

This patch implements a Value class that can be used to carry expression
results in clang-repl. In other words, when we see a top expression
without semi, it will be captured and stored to a Value object. You can
explicitly specify where you want to store the object, like:

```
Value V;
llvm::cantFail(Interp->ParseAndExecute("int x = 42;"));
llvm::cantFail(Interp->ParseAndExecute("x", ));
```

`V` now stores some useful infomation about `x`, you can get its real
value (42), it's `clang::QualType` or anything interesting.

However, if you don't specify the optional argument, it will be captured
to a local variable, and automatically called `Value::dump`, which is
not implemented yet in this patch.

Signed-off-by: Jun Zhang 

Added: 
clang/include/clang/Interpreter/Value.h
clang/lib/Interpreter/InterpreterUtils.cpp
clang/lib/Interpreter/InterpreterUtils.h
clang/lib/Interpreter/Value.cpp

Modified: 
clang/include/clang/Interpreter/Interpreter.h
clang/lib/Interpreter/CMakeLists.txt
clang/lib/Interpreter/IncrementalParser.cpp
clang/lib/Interpreter/IncrementalParser.h
clang/lib/Interpreter/Interpreter.cpp
clang/tools/clang-repl/CMakeLists.txt
clang/unittests/Interpreter/CMakeLists.txt
clang/unittests/Interpreter/InterpreterTest.cpp

Removed: 




diff  --git a/clang/include/clang/Interpreter/Interpreter.h 
b/clang/include/clang/Interpreter/Interpreter.h
index b3d64458d777c..e680218452d1c 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -14,14 +14,15 @@
 #ifndef LLVM_CLANG_INTERPRETER_INTERPRETER_H
 #define LLVM_CLANG_INTERPRETER_INTERPRETER_H
 
-#include "clang/Interpreter/PartialTranslationUnit.h"
-
+#include "clang/AST/Decl.h"
 #include "clang/AST/GlobalDecl.h"
+#include "clang/Interpreter/PartialTranslationUnit.h"
+#include "clang/Interpreter/Value.h"
 
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ExecutionEngine/JITSymbol.h"
 #include "llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h"
 #include "llvm/Support/Error.h"
-
 #include 
 #include 
 
@@ -54,24 +55,26 @@ class Interpreter {
   Interpreter(std::unique_ptr CI, llvm::Error );
 
   llvm::Error CreateExecutor();
+  unsigned InitPTUSize = 0;
+
+  // This member holds the last result of the value printing. It's a class
+  // member because we might want to access it after more inputs. If no value
+  // printing happens, it's in an invalid state.
+  Value LastValue;
 
 public:
   ~Interpreter();
   static llvm::Expected>
   create(std::unique_ptr CI);
+  const ASTContext () const;
+  ASTContext ();
   const CompilerInstance *getCompilerInstance() const;
   llvm::Expected getExecutionEngine();
 
   llvm::Expected Parse(llvm::StringRef Code);
   llvm::Error Execute(PartialTranslationUnit );
-  llvm::Error ParseAndExecute(llvm::StringRef Code) {
-auto PTU = Parse(Code);
-if (!PTU)
-  return PTU.takeError();
-if (PTU->TheModule)
-  return Execute(*PTU);
-return llvm::Error::success();
-  }
+  llvm::Error ParseAndExecute(llvm::StringRef Code, Value *V = nullptr);
+  llvm::Expected CompileDtorCall(CXXRecordDecl 
*CXXRD);
 
   /// Undo N previous incremental inputs.
   llvm::Error Undo(unsigned N = 1);
@@ -92,6 +95,23 @@ class Interpreter {
   /// file.
   llvm::Expected
   getSymbolAddressFromLinkerName(llvm::StringRef LinkerName) const;
+
+  enum InterfaceKind { NoAlloc, WithAlloc, CopyArray };
+
+  const llvm::SmallVectorImpl () const {
+return ValuePrintingInfo;
+  }
+
+  Expr *SynthesizeExpr(Expr *E);
+
+private:
+  size_t getEffectivePTUSize() const;
+
+  bool FindRuntimeInterface();
+
+  llvm::DenseMap Dtors;
+
+  llvm::SmallVector ValuePrintingInfo;
 };
 } // namespace clang
 

diff  --git a/clang/include/clang/Interpreter/Value.h 
b/clang/include/clang/Interpreter/Value.h
new file mode 100644
index 0..90a0097e5cc37
--- /dev/null
+++ b/clang/include/clang/Interpreter/Value.h
@@ -0,0 +1,200 @@
+//===--- Value.h - Definition of interpreter value --*- 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
+//
+//===--===//
+//
+// Value is a lightweight struct that is used for carrying execution results in

[clang] 247fa04 - [clang] Add a new annotation token: annot_repl_input_end

2023-05-16 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2023-05-16T20:10:43+08:00
New Revision: 247fa04116a6cabf8378c6c72d90b2f705e969de

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

LOG: [clang] Add a new annotation token: annot_repl_input_end

This patch is the first part of the below RFC:
https://discourse.llvm.org/t/rfc-handle-execution-results-in-clang-repl/68493

It adds an annotation token which will replace the original EOF token
when we are in the incremental C++ mode. In addition, when we're
parsing an ExprStmt and there's a missing semicolon after the
expression, we set a marker in the annotation token and continue
parsing.

Eventually, we propogate this info in ParseTopLevelStmtDecl and are able
to mark this Decl as something we want to do value printing. Below is a
example:

clang-repl> int x = 42;
clang-repl> x
// `x` is a TopLevelStmtDecl and without a semicolon, we should set
// it's IsSemiMissing bit so we can do something interesting in
// ASTConsumer::HandleTopLevelDecl.

The idea about annotation toke is proposed by Richard Smith, thanks!

Signed-off-by: Jun Zhang 

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

Added: 


Modified: 
clang/include/clang/AST/Decl.h
clang/include/clang/Basic/TokenKinds.def
clang/include/clang/Parse/Parser.h
clang/lib/Frontend/PrintPreprocessedOutput.cpp
clang/lib/Interpreter/IncrementalParser.cpp
clang/lib/Lex/PPLexerChange.cpp
clang/lib/Parse/ParseCXXInlineMethods.cpp
clang/lib/Parse/ParseDecl.cpp
clang/lib/Parse/ParseStmt.cpp
clang/lib/Parse/Parser.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 650baf56414c7..37512ccb81e59 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -4324,6 +4324,7 @@ class TopLevelStmtDecl : public Decl {
   friend class ASTDeclWriter;
 
   Stmt *Statement = nullptr;
+  bool IsSemiMissing = false;
 
   TopLevelStmtDecl(DeclContext *DC, SourceLocation L, Stmt *S)
   : Decl(TopLevelStmt, DC, L), Statement(S) {}
@@ -4337,6 +4338,12 @@ class TopLevelStmtDecl : public Decl {
   SourceRange getSourceRange() const override LLVM_READONLY;
   Stmt *getStmt() { return Statement; }
   const Stmt *getStmt() const { return Statement; }
+  void setStmt(Stmt *S) {
+assert(IsSemiMissing && "Operation supported for printing values only!");
+Statement = S;
+  }
+  bool isSemiMissing() const { return IsSemiMissing; }
+  void setSemiMissing(bool Missing = true) { IsSemiMissing = Missing; }
 
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classofKind(Kind K) { return K == TopLevelStmt; }

diff  --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index f17a6028a137a..ae67209d9b9e2 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -942,6 +942,9 @@ ANNOTATION(module_end)
 // into the name of a header unit.
 ANNOTATION(header_unit)
 
+// Annotation for end of input in clang-repl.
+ANNOTATION(repl_input_end)
+
 #undef PRAGMA_ANNOTATION
 #undef ANNOTATION
 #undef TESTING_KEYWORD

diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index fc892d71b51bf..17aa11b74add1 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -18,6 +18,7 @@
 #include "clang/Basic/OpenMPKinds.h"
 #include "clang/Basic/OperatorPrecedence.h"
 #include "clang/Basic/Specifiers.h"
+#include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/CodeCompletionHandler.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Sema/DeclSpec.h"
@@ -692,7 +693,8 @@ class Parser : public CodeCompletionHandler {
   bool isEofOrEom() {
 tok::TokenKind Kind = Tok.getKind();
 return Kind == tok::eof || Kind == tok::annot_module_begin ||
-   Kind == tok::annot_module_end || Kind == tok::annot_module_include;
+   Kind == tok::annot_module_end || Kind == tok::annot_module_include 
||
+   Kind == tok::annot_repl_input_end;
   }
 
   /// Checks if the \p Level is valid for use in a fold expression.

diff  --git a/clang/lib/Frontend/PrintPreprocessedOutput.cpp 
b/clang/lib/Frontend/PrintPreprocessedOutput.cpp
index ffa85e523c038..1b262d9e6f7cb 100644
--- a/clang/lib/Frontend/PrintPreprocessedOutput.cpp
+++ b/clang/lib/Frontend/PrintPreprocessedOutput.cpp
@@ -663,7 +663,8 @@ void 
PrintPPOutputPPCallbacks::HandleWhitespaceBeforeTok(const Token ,
   // them.
   if (Tok.is(tok::eof) ||
   (Tok.isAnnotation() && !Tok.is(tok::annot_header_unit) &&
-   !Tok.is(tok::annot_module_begin) && !Tok.is(tok::annot_module_end)))
+   !Tok.is(tok::annot_module_begin) && !Tok.is(tok::annot_module_end) &&
+   

[clang] fe1f344 - [clang-repl] JITTargetAddress --> ExecutorAddr, NFC

2023-04-15 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2023-04-16T09:46:44+08:00
New Revision: fe1f34453d7ef2c0d5f308e0abdb185d6807cfa6

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

LOG: [clang-repl] JITTargetAddress --> ExecutorAddr, NFC

Most of Orc and JITLink are movinng away from JITTargetAddress and
use ExecutorAddr instead.

Signed-off-by: Jun Zhang 

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

Added: 


Modified: 
clang/include/clang/Interpreter/Interpreter.h
clang/lib/Interpreter/IncrementalExecutor.cpp
clang/lib/Interpreter/IncrementalExecutor.h
clang/lib/Interpreter/Interpreter.cpp
clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp
clang/unittests/Interpreter/InterpreterTest.cpp

Removed: 




diff  --git a/clang/include/clang/Interpreter/Interpreter.h 
b/clang/include/clang/Interpreter/Interpreter.h
index b20d77e8ef853..b3d64458d777c 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -19,6 +19,7 @@
 #include "clang/AST/GlobalDecl.h"
 
 #include "llvm/ExecutionEngine/JITSymbol.h"
+#include "llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h"
 #include "llvm/Support/Error.h"
 
 #include 
@@ -78,18 +79,18 @@ class Interpreter {
   /// Link a dynamic library
   llvm::Error LoadDynamicLibrary(const char *name);
 
-  /// \returns the \c JITTargetAddress of a \c GlobalDecl. This interface uses
+  /// \returns the \c ExecutorAddr of a \c GlobalDecl. This interface uses
   /// the CodeGenModule's internal mangling cache to avoid recomputing the
   /// mangled name.
-  llvm::Expected getSymbolAddress(GlobalDecl GD) const;
+  llvm::Expected getSymbolAddress(GlobalDecl GD) 
const;
 
-  /// \returns the \c JITTargetAddress of a given name as written in the IR.
-  llvm::Expected
+  /// \returns the \c ExecutorAddr of a given name as written in the IR.
+  llvm::Expected
   getSymbolAddress(llvm::StringRef IRName) const;
 
-  /// \returns the \c JITTargetAddress of a given name as written in the object
+  /// \returns the \c ExecutorAddr of a given name as written in the object
   /// file.
-  llvm::Expected
+  llvm::Expected
   getSymbolAddressFromLinkerName(llvm::StringRef LinkerName) const;
 };
 } // namespace clang

diff  --git a/clang/lib/Interpreter/IncrementalExecutor.cpp 
b/clang/lib/Interpreter/IncrementalExecutor.cpp
index d744270d486a1..fdf12dd214148 100644
--- a/clang/lib/Interpreter/IncrementalExecutor.cpp
+++ b/clang/lib/Interpreter/IncrementalExecutor.cpp
@@ -77,7 +77,7 @@ llvm::Error IncrementalExecutor::runCtors() const {
   return Jit->initialize(Jit->getMainJITDylib());
 }
 
-llvm::Expected
+llvm::Expected
 IncrementalExecutor::getSymbolAddress(llvm::StringRef Name,
   SymbolNameKind NameKind) const {
   auto Sym = (NameKind == LinkerName) ? Jit->lookupLinkerMangled(Name)
@@ -85,7 +85,7 @@ IncrementalExecutor::getSymbolAddress(llvm::StringRef Name,
 
   if (!Sym)
 return Sym.takeError();
-  return Sym->getValue();
+  return Sym;
 }
 
 } // end namespace clang

diff  --git a/clang/lib/Interpreter/IncrementalExecutor.h 
b/clang/lib/Interpreter/IncrementalExecutor.h
index f7922ecb53800..dd0a210a06141 100644
--- a/clang/lib/Interpreter/IncrementalExecutor.h
+++ b/clang/lib/Interpreter/IncrementalExecutor.h
@@ -16,6 +16,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
+#include "llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h"
 
 #include 
 
@@ -51,7 +52,7 @@ class IncrementalExecutor {
   llvm::Error removeModule(PartialTranslationUnit );
   llvm::Error runCtors() const;
   llvm::Error cleanUp();
-  llvm::Expected
+  llvm::Expected
   getSymbolAddress(llvm::StringRef Name, SymbolNameKind NameKind) const;
 
   llvm::orc::LLJIT () { return *Jit; }

diff  --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index a0ccbc20b95f4..24fb9da69a8bc 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -246,7 +246,7 @@ llvm::Error Interpreter::Execute(PartialTranslationUnit ) 
{
   return llvm::Error::success();
 }
 
-llvm::Expected
+llvm::Expected
 Interpreter::getSymbolAddress(GlobalDecl GD) const {
   if (!IncrExecutor)
 return llvm::make_error("Operation failed. "
@@ -256,7 +256,7 @@ Interpreter::getSymbolAddress(GlobalDecl GD) const {
   return getSymbolAddress(MangledName);
 }
 
-llvm::Expected
+llvm::Expected
 Interpreter::getSymbolAddress(llvm::StringRef IRName) const {
   if (!IncrExecutor)
 return llvm::make_error("Operation failed. "
@@ -266,7 +266,7 @@ Interpreter::getSymbolAddress(llvm::StringRef IRName) const 
{
   return IncrExecutor->getSymbolAddress(IRName, 

[clang] eda2eaa - [clang][dataflow] Fix crash when having boolean-to-integral casts.

2022-12-29 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-12-30T13:14:44+08:00
New Revision: eda2eaabf2949c08ba94c92b9aad6fccb3c8eaa2

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

LOG: [clang][dataflow] Fix crash when having boolean-to-integral casts.

Since now we just ignore all (implicit) integral casts, treating the
resulting value as the same as the underlying value, it could cause
inconsistency between values after `Join` if in some paths the type
doesn't strictly match. This could cause intermittent crashes.

std::optional o;
int x;
if (o.has_value()) {
  x = o.value();
}

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

Signed-off-by: Jun Zhang 

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

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index c883f90f5554b..b8e3e93390602 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -93,7 +93,19 @@ static Value *mergeDistinctValues(QualType Type, Value ,
   Environment::ValueModel ) {
   // Join distinct boolean values preserving information about the constraints
   // in the respective path conditions.
-  if (auto *Expr1 = dyn_cast()) {
+  if (Type->isBooleanType()) {
+// FIXME: The type check above is a workaround and should be unnecessary.
+// However, right now we can end up with BoolValue's in integer-typed
+// variables due to our incorrect handling of boolean-to-integer casts (we
+// just propagate the BoolValue to the result of the cast). For example:
+// std::optional o;
+//
+//
+// int x;
+// if (o.has_value()) {
+//   x = o.value();
+// }
+auto *Expr1 = cast();
 auto *Expr2 = cast();
 auto  = MergedEnv.makeAtomicBoolValue();
 MergedEnv.addToFlowCondition(MergedEnv.makeOr(

diff  --git 
a/clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
index 4d9c57f0dacd5..1fcede5d62865 100644
--- 
a/clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ 
b/clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -2970,6 +2970,23 @@ TEST_P(UncheckedOptionalAccessTest, 
CtorInitializerValue) {
   cxxConstructorDecl(ofClass(hasName("Target";
 }
 
+// This is regression test, it shouldn't crash.
+TEST_P(UncheckedOptionalAccessTest, Bitfield) {
+  using namespace ast_matchers;
+  ExpectDiagnosticsFor(
+  R"(
+#include "unchecked_optional_access_test.h"
+struct Dst {
+  unsigned int n : 1;
+};
+void target() {
+  $ns::$optional v;
+  Dst d;
+  if (v.has_value())
+d.n = v.value();
+}
+  )");
+}
 // FIXME: Add support for:
 // - constructors (copy, move)
 // - assignment operators (default, copy, move)



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


[clang-tools-extra] 4fd0c14 - Link with missing libs to fix broken shared unittest build

2022-12-02 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-12-03T01:10:13+08:00
New Revision: 4fd0c14a17f91fb7b0d188b509eb3dbdfbfec01a

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

LOG: Link with missing libs to fix broken shared unittest build

Oops, I think we should link with this as well.

Signed-off-by: Jun Zhang 

Added: 


Modified: 
clang-tools-extra/include-cleaner/unittests/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/unittests/CMakeLists.txt 
b/clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
index d911b5df70c50..e5a4180a53e31 100644
--- a/clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
+++ b/clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
@@ -22,6 +22,7 @@ clang_target_link_libraries(ClangIncludeCleanerTests
   clangAST
   clangBasic
   clangFrontend
+  clangFormat
   clangLex
   clangToolingInclusionsStdlib
   )



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


[clang-tools-extra] 8431436 - Link with missing libs to fix broken shared build

2022-12-02 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-12-03T00:01:37+08:00
New Revision: 8431436e543f78a33e8165257f2e2f89c38269f9

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

LOG: Link with missing libs to fix broken shared build

Signed-off-by: Jun Zhang 

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

Added: 


Modified: 
clang-tools-extra/include-cleaner/lib/CMakeLists.txt
clang-tools-extra/include-cleaner/tool/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/lib/CMakeLists.txt 
b/clang-tools-extra/include-cleaner/lib/CMakeLists.txt
index 5c83e8fdc1515..75e1fb725c656 100644
--- a/clang-tools-extra/include-cleaner/lib/CMakeLists.txt
+++ b/clang-tools-extra/include-cleaner/lib/CMakeLists.txt
@@ -16,6 +16,7 @@ clang_target_link_libraries(clangIncludeCleaner
   clangBasic
   clangFormat
   clangLex
+  clangToolingCore
   clangToolingInclusions
   clangToolingInclusionsStdlib
   )

diff  --git a/clang-tools-extra/include-cleaner/tool/CMakeLists.txt 
b/clang-tools-extra/include-cleaner/tool/CMakeLists.txt
index 3b9b03141ce1b..f48907f9ae68a 100644
--- a/clang-tools-extra/include-cleaner/tool/CMakeLists.txt
+++ b/clang-tools-extra/include-cleaner/tool/CMakeLists.txt
@@ -6,6 +6,7 @@ clang_target_link_libraries(clang-include-cleaner PRIVATE
   clangBasic
   clangFrontend
   clangLex
+  clangFormat
   clangSerialization
   clangTooling
   )



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


[clang] 2946b25 - [Clang] Fix crash when checking misaligned member with dependent type

2022-10-18 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-10-18T21:05:49+08:00
New Revision: 2946b252993d9b4c12479bf318b648bed2c0427a

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

LOG: [Clang] Fix crash when checking misaligned member with dependent type

If the type is dependent, we should just discard it and not checking its
alignment as it doesn't exisit yet.
Fixes https://github.com/llvm/llvm-project/issues/58370

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

Added: 
clang/test/SemaCXX/misaligned-member-with-depdent-type.cpp

Modified: 
clang/lib/Sema/SemaChecking.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index c0ecd7b091000..9d8640a6a057a 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -17387,15 +17387,15 @@ void Sema::DiagnoseMisalignedMembers() {
 
 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
   E = E->IgnoreParens();
-  if (!T->isPointerType() && !T->isIntegerType())
+  if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
 return;
   if (isa(E) &&
   cast(E)->getOpcode() == UO_AddrOf) {
 auto *Op = cast(E)->getSubExpr()->IgnoreParens();
 if (isa(Op)) {
-  auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
+  auto *MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
   if (MA != MisalignedMembers.end() &&
-  (T->isIntegerType() ||
+  (T->isDependentType() || T->isIntegerType() ||
(T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
Context.getTypeAlignInChars(
T->getPointeeType()) <= 
MA->Alignment

diff  --git a/clang/test/SemaCXX/misaligned-member-with-depdent-type.cpp 
b/clang/test/SemaCXX/misaligned-member-with-depdent-type.cpp
new file mode 100644
index 0..cd4768350bab4
--- /dev/null
+++ b/clang/test/SemaCXX/misaligned-member-with-depdent-type.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+struct __attribute__((packed)) {
+  unsigned options;
+  template 
+  void getOptions() {
+  (T *)
+  }
+  template 
+   void getOptions2() {
+  (U)
+   }
+} s;
+
+struct __attribute__((packed)) { // expected-error {{anonymous structs and 
classes must be class members}}
+   unsigned options ;
+  template  getOptions() // expected-error {{a type specifier is 
required for all declarations}}
+{
+  (T *) & options;
+}
+};



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


[clang] 89e56e7 - [Clang] Don't warn if deferencing void pointers in unevaluated context

2022-09-27 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-09-28T12:30:02+08:00
New Revision: 89e56e732d5e89d8715a501158793ac305bc4b70

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

LOG: [Clang] Don't warn if deferencing void pointers in unevaluated context

After https://reviews.llvm.org/D134461, Clang will diagnose a warning if
trying to deference void pointers in C mode. However, this causes a lot
of noises when compiling a 5.19.11 Linux kernel.

This patch reduces the warning by marking deferencing void pointers in
unevaluated context OK, like `sizeof(*void_ptr)`, `typeof(*void_ptr)`
and etc.

Fixes https://github.com/ClangBuiltLinux/linux/issues/1720

Signed-off-by: Jun Zhang 

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

Added: 
clang/test/Sema/no-warn-void-ptr-uneval.c

Modified: 
clang/lib/Sema/SemaExpr.cpp
clang/test/Analysis/misc-ps.m

Removed: 




diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index acbf7d534d49f..fca9240362e76 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -14536,7 +14536,7 @@ static QualType CheckIndirectionOperand(Sema , Expr 
*Op, ExprValueKind ,
 //   [...] the expression to which [the unary * operator] is applied shall
 //   be a pointer to an object type, or a pointer to a function type
 LangOptions LO = S.getLangOpts();
-if (LO.CPlusPlus || !(LO.C99 && IsAfterAmp))
+if (LO.CPlusPlus || !(LO.C99 && (IsAfterAmp || S.isUnevaluatedContext(
   S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
   << LO.CPlusPlus << OpTy << Op->getSourceRange();
   }

diff  --git a/clang/test/Analysis/misc-ps.m b/clang/test/Analysis/misc-ps.m
index 4e3783dfc93ac..e9e56315eb268 100644
--- a/clang/test/Analysis/misc-ps.m
+++ b/clang/test/Analysis/misc-ps.m
@@ -133,7 +133,7 @@ void handle_sizeof_void(unsigned flag) {
   void* q;
   
   if (!flag) {
-if (sizeof(*q) == 1) // expected-warning {{ISO C does not allow 
indirection on operand of type 'void *'}}
+if (sizeof(*q) == 1)
   return;
 // Infeasibe.
 *p = 1; // no-warning

diff  --git a/clang/test/Sema/no-warn-void-ptr-uneval.c 
b/clang/test/Sema/no-warn-void-ptr-uneval.c
new file mode 100644
index 0..2aed1180ab0da
--- /dev/null
+++ b/clang/test/Sema/no-warn-void-ptr-uneval.c
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -fsyntax-only -Wno-unused-value -verify %s
+
+// expected-no-diagnostics
+void foo(void *vp) {
+  sizeof(*vp);
+  sizeof(*(vp));
+  void inner(typeof(*vp));
+}



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


[clang] e07ead8 - [Clang] Warn when trying to dereference void pointers in C

2022-09-24 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-09-24T22:18:04+08:00
New Revision: e07ead85a368173a56e96a21d6841aa497ad80f8

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

LOG: [Clang] Warn when trying to dereference void pointers in C

Previously we only have an extension that warn void pointer deferencing
in C++, but for C we did nothing.

C2x 6.5.3.2p4 says The unary * operator denotes indirection. If it points
to an object, the result is an lvalue designating the object. However, there
is no way to form an lvalue designating an object of an incomplete type as
6.3.2.1p1 says "an lvalue is an expression (with an object type other than
void)", so the behavior is undefined.

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

Signed-off-by: Jun Zhang 

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/Parse/ParseExpr.cpp
clang/lib/Sema/SemaExpr.cpp
clang/test/Analysis/misc-ps.m
clang/test/C/drs/dr0xx.c
clang/test/C/drs/dr1xx.c
clang/test/Sema/asm.c
clang/test/Sema/builtins-arm.c
clang/test/Sema/conditional-expr.c
clang/test/Sema/deref.c
clang/test/Sema/expr-address-of.c
clang/test/Sema/i-c-e.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ed262823d004d..a5e72fc917f38 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -210,6 +210,8 @@ Improvements to Clang's diagnostics
   ``LL`` suffix.
 - Clang now correctly diagnoses index that refers past the last possible 
element
   of FAM-like arrays.
+- Clang now correctly diagnoses a warning when defercencing a void pointer in 
C mode.
+  This fixes `Issue 53631 `_
 
 Non-comprehensive list of changes in this release
 -

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 7647aa929b75e..834b60a2744d6 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6919,7 +6919,7 @@ def err_typecheck_unary_expr : Error<
 def err_typecheck_indirection_requires_pointer : Error<
   "indirection requires pointer operand (%0 invalid)">;
 def ext_typecheck_indirection_through_void_pointer : ExtWarn<
-  "ISO C++ does not allow indirection on operand of type %0">,
+  "ISO %select{C|C++}0 does not allow indirection on operand of type %1">,
   InGroup>;
 def warn_indirection_through_null : Warning<
   "indirection of non-volatile null pointer will be deleted, not trap">,

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 8628ed48481f2..b6fd8174e1d87 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -5604,11 +5604,11 @@ class Sema final {
 
   // Binary/Unary Operators.  'Tok' is the token for the operator.
   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
-  Expr *InputExpr);
-  ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
-  UnaryOperatorKind Opc, Expr *Input);
-  ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
-  tok::TokenKind Op, Expr *Input);
+  Expr *InputExpr, bool IsAfterAmp = false);
+  ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind 
Opc,
+  Expr *Input, bool IsAfterAmp = false);
+  ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
+  Expr *Input, bool IsAfterAmp = false);
 
   bool isQualifiedMemberAccess(Expr *E);
   QualType CheckAddressOfOperand(ExprResult , SourceLocation OpLoc);

diff  --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp
index 77e8b9488a8c9..9b3c39e7b43fb 100644
--- a/clang/lib/Parse/ParseExpr.cpp
+++ b/clang/lib/Parse/ParseExpr.cpp
@@ -1360,7 +1360,8 @@ ExprResult Parser::ParseCastExpression(CastParseKind 
ParseKind,
 // Special treatment because of member pointers
 SourceLocation SavedLoc = ConsumeToken();
 PreferredType.enterUnary(Actions, Tok.getLocation(), tok::amp, SavedLoc);
-Res = ParseCastExpression(AnyCastExpr, true);
+
+Res = ParseCastExpression(AnyCastExpr, /*isAddressOfOperand=*/true);
 if (!Res.isInvalid()) {
   Expr *Arg = Res.get();
   Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg);
@@ -1385,7 +1386,8 @@ ExprResult Parser::ParseCastExpression(CastParseKind 
ParseKind,
 Res = ParseCastExpression(AnyCastExpr);
 if 

[clang] 303526e - [Docs] Add a link that refers to C++ standard modules in Clang modules doc

2022-09-18 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-09-18T18:31:49+08:00
New Revision: 303526ef3aa211c1930be2885deae15eeeda3b18

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

LOG: [Docs] Add a link that refers to C++ standard modules in Clang modules doc

Currently there're two pages that both talk about "Modules" in clang, but
they're different. The one that describes C++ standard modules explicitly
spells out the difference but the other one which targeting Clang modules
doesn't.

This patch adds a link that refers to the C++ standard modules
one in Clang modules doc, as you usually got the later page when
googling. I believe this will make newcomers less confused.

Signed-off-by: Jun Zhang 

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

Added: 


Modified: 
clang/docs/Modules.rst

Removed: 




diff  --git a/clang/docs/Modules.rst b/clang/docs/Modules.rst
index d85a60e881837..825d8722c4d53 100644
--- a/clang/docs/Modules.rst
+++ b/clang/docs/Modules.rst
@@ -102,6 +102,11 @@ Using Modules
 =
 To enable modules, pass the command-line flag ``-fmodules``. This will make 
any modules-enabled software libraries available as modules as well as 
introducing any modules-specific syntax. Additional `command-line parameters`_ 
are described in a separate section later.
 
+Standard C++ Modules
+
+.. note::
+  Modules are adopted into C++20 Standard. And its semantic and command line 
interface are very 
diff erent from the Clang C++ modules. See `StandardCPlusPlusModules 
`_ for details.
+
 Objective-C Import declaration
 --
 Objective-C provides syntax for importing a module via an *@import 
declaration*, which imports the named module:



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


[clang] 1d51bb8 - [Clang] Reword diagnostic for scope identifier with linkage

2022-09-12 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-09-12T22:40:54+08:00
New Revision: 1d51bb824f25140a5b1aa783f6860ac3e7f7d16d

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

LOG: [Clang] Reword diagnostic for scope identifier with linkage

If the declaration of an identifier has block scope, and the identifier has
external or internal linkage, the declaration shall have no initializer for
the identifier.

Clang now gives a more suitable diagnosis for this case.
Fixes https://github.com/llvm/llvm-project/issues/57478

Signed-off-by: Jun Zhang 

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

Added: 
clang/test/Sema/err-decl-block-extern-no-init.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaDecl.cpp
clang/test/Parser/cxx1z-decomposition.cpp
clang/test/Sema/array-init.c
clang/test/Sema/private-extern.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 75a57c5d18d8b..30402411178d4 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -138,6 +138,9 @@ Improvements to Clang's diagnostics
   incorrectly saying no_sanitize only applies to functions and methods.
 - No longer mention ``reinterpet_cast`` in the invalid constant expression
   diagnostic note when in C mode.
+- Clang will now give a more suitale diagnostic for declaration of block
+  scope identifiers that have external/internal linkage that has an 
initializer.
+  Fixes `Issue 57478: `_.
 
 Non-comprehensive list of changes in this release
 -

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 76e18c9deff46..016affb1b3236 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5901,7 +5901,7 @@ def err_loader_uninitialized_extern_decl
 : Error<"variable %0 cannot be declared both 'extern' and with the "
 "'loader_uninitialized' attribute">;
 def err_block_extern_cant_init : Error<
-  "'extern' variable cannot have an initializer">;
+  "declaration of block scope identifier with linkage cannot have an 
initializer">;
 def warn_extern_init : Warning<"'extern' variable has an initializer">,
   InGroup>;
 def err_variable_object_no_init : Error<

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 2ad6edc121ae9..6e94da4a115eb 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -12773,8 +12773,11 @@ void Sema::AddInitializerToDecl(Decl *RealDecl, Expr 
*Init, bool DirectInit) {
 return;
   }
 
+  // C99 6.7.8p5. If the declaration of an identifier has block scope, and
+  // the identifier has external or internal linkage, the declaration shall
+  // have no initializer for the identifier.
+  // C++14 [dcl.init]p5 is the same restriction for C++.
   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
-// C99 6.7.8p5. C++ has no such restriction, but that is a defect.
 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
 VDecl->setInvalidDecl();
 return;

diff  --git a/clang/test/Parser/cxx1z-decomposition.cpp 
b/clang/test/Parser/cxx1z-decomposition.cpp
index 7abf1f9cdac56..10ef464bda50c 100644
--- a/clang/test/Parser/cxx1z-decomposition.cpp
+++ b/clang/test/Parser/cxx1z-decomposition.cpp
@@ -69,7 +69,7 @@ namespace BadSpecifiers {
 // storage-class-specifiers
 static auto &[a] = n; // expected-warning {{declared 'static' is a C++20 
extension}}
 thread_local auto &[b] = n; // expected-warning {{declared 'thread_local' 
is a C++20 extension}}
-extern auto &[c] = n; // expected-error {{cannot be declared 'extern'}} 
expected-error {{cannot have an initializer}}
+extern auto &[c] = n; // expected-error {{cannot be declared 'extern'}} 
expected-error {{declaration of block scope identifier with linkage cannot have 
an initializer}}
 struct S {
   mutable auto &[d] = n; // expected-error {{not permitted in this 
context}}
 

diff  --git a/clang/test/Sema/array-init.c b/clang/test/Sema/array-init.c
index ae3ce73ccc7a3..fcc3c13bc91da 100644
--- a/clang/test/Sema/array-init.c
+++ b/clang/test/Sema/array-init.c
@@ -48,7 +48,7 @@ void func(void) {
 
   struct threeElements *p = 7; // expected-error{{incompatible integer to 
pointer conversion initializing 'struct threeElements *' with an expression of 
type 'int'}}
 
-  extern int blockScopeExtern[3] = { 1, 3, 5 }; // expected-error{{'extern' 
variable cannot have an initializer}}
+  extern int blockScopeExtern[3] = { 1, 3, 5 }; // expected-error{{declaration 
of block scope 

[clang] b9c2b60 - Avoid else-if after return, NFC

2022-08-27 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-08-27T23:14:48+08:00
New Revision: b9c2b6069ea7f3d253d88725c1993da463f39575

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

LOG: Avoid else-if after return, NFC

Signed-off-by: Jun Zhang 

Added: 


Modified: 
clang/lib/Basic/SourceManager.cpp

Removed: 




diff  --git a/clang/lib/Basic/SourceManager.cpp 
b/clang/lib/Basic/SourceManager.cpp
index 38545d1be918f..24e4aefd53f1c 100644
--- a/clang/lib/Basic/SourceManager.cpp
+++ b/clang/lib/Basic/SourceManager.cpp
@@ -1795,11 +1795,11 @@ void SourceManager::computeMacroArgsCache(MacroArgsMap 
,
 if (Entry.getFile().NumCreatedFIDs)
   ID += Entry.getFile().NumCreatedFIDs - 1 /*because of next ++ID*/;
 continue;
-  } else if (IncludeLoc.isValid()) {
-// If file was included but not from FID, there is no more files/macros
-// that may be "contained" in this file.
-return;
   }
+  // If file was included but not from FID, there is no more files/macros
+  // that may be "contained" in this file.
+  if (IncludeLoc.isValid())
+return;
   continue;
 }
 



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


[clang] a4f84f1 - [CodeGen] Track DeferredDecls that have been emitted

2022-08-27 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-08-27T22:32:47+08:00
New Revision: a4f84f1b2e92ea79b70b9961049a1af7d9e1f2fa

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

LOG: [CodeGen] Track DeferredDecls that have been emitted

If we run into a first usage or definition of a mangled name, and
there's a DeferredDecl that associated with it, we should remember it we
need to emit it later on.

Without this patch, clang-repl hits a JIT symbol not found error:
clang-repl> extern "C" int printf(const char *, ...);
clang-repl> auto l1 = []() { printf("ONE\n"); return 42; };
clang-repl> auto l2 = []() { printf("TWO\n"); return 17; };
clang-repl> auto r1 = l1();
ONE
clang-repl> auto r2 = l2();
TWO
clang-repl> auto r3 = l2();
JIT session error: Symbols not found: [ l2 ]
error: Failed to materialize symbols: { (main,
{ r3, orc_init_func.incr_module_5, $.incr_module_5.inits.0 }) }

Signed-off-by: Jun Zhang 

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

Added: 
clang/test/Interpreter/lambda.cpp

Modified: 
clang/lib/CodeGen/CodeGenModule.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 2ced1c5419813..6294fe9e87d32 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3356,6 +3356,7 @@ void CodeGenModule::EmitGlobal(GlobalDecl GD) {
 // The value must be emitted, but cannot be emitted eagerly.
 assert(!MayBeEmittedEagerly(Global));
 addDeferredDeclToEmit(GD);
+EmittedDeferredDecls[MangledName] = GD;
   } else {
 // Otherwise, remember that we saw a deferred decl with this name.  The
 // first use of the mangled name will cause it to move into
@@ -4073,6 +4074,7 @@ llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
   // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
   // don't need it anymore).
   addDeferredDeclToEmit(DDI->second);
+  EmittedDeferredDecls[DDI->first] = DDI->second;
   DeferredDecls.erase(DDI);
 
   // Otherwise, there are cases we have to worry about where we're
@@ -4354,6 +4356,7 @@ CodeGenModule::GetOrCreateLLVMGlobal(StringRef 
MangledName, llvm::Type *Ty,
 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
 // list, and remove it from DeferredDecls (since we don't need it anymore).
 addDeferredDeclToEmit(DDI->second);
+EmittedDeferredDecls[DDI->first] = DDI->second;
 DeferredDecls.erase(DDI);
   }
 

diff  --git a/clang/test/Interpreter/lambda.cpp 
b/clang/test/Interpreter/lambda.cpp
new file mode 100644
index 0..d06009d59fe08
--- /dev/null
+++ b/clang/test/Interpreter/lambda.cpp
@@ -0,0 +1,21 @@
+// RUN: clang-repl "int x = 10;" "int y=7; err;" "int y = 10;"
+// RUN: clang-repl "int i = 10;" 'extern "C" int printf(const char*,...);' \
+// RUN:'auto r1 = printf("i = %d\n", i);' | FileCheck 
--check-prefix=CHECK-DRIVER %s
+// REQUIRES: host-supports-jit
+// UNSUPPORTED: system-aix
+// CHECK-DRIVER: i = 10
+// RUN: cat %s | clang-repl | FileCheck %s
+// RUN: cat %s | clang-repl -Xcc -O2 | FileCheck %s
+extern "C" int printf(const char *, ...);
+
+auto l1 = []() { printf("ONE\n"); return 42; };
+auto l2 = []() { printf("TWO\n"); return 17; };
+
+auto r1 = l1();
+// CHECK: ONE
+auto r2 = l2();
+// CHECK: TWO
+auto r3 = l2();
+// CHECK: TWO
+
+%quit



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


[clang] efc75a2 - Remove redundant condition check, NFC

2022-08-11 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-08-11T21:47:19+08:00
New Revision: efc75a2baedc7405193e3e0f5ea9aaa881783cec

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

LOG: Remove redundant condition check, NFC

Signed-off-by: Jun Zhang 

Added: 


Modified: 
clang/lib/Parse/ParseDecl.cpp

Removed: 




diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 72d4804a1758e..39ba93ee33859 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -2078,10 +2078,8 @@ Parser::DeclGroupPtrTy 
Parser::ParseDeclGroup(ParsingDeclSpec ,
   << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
 : FixItHint());
 }
-  }
 
-  // Check to see if we have a function *definition* which must have a body.
-  if (D.isFunctionDeclarator()) {
+// Check to see if we have a function *definition* which must have a body.
 if (Tok.is(tok::equal) && NextToken().is(tok::code_completion)) {
   cutOffParsing();
   Actions.CodeCompleteAfterFunctionEquals(D);



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


[clang] 786b503 - [Clang][Lex] Extend HeaderSearch::LookupFile to control OpenFile behavior.

2022-08-05 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-08-06T11:36:02+08:00
New Revision: 786b503f66b1a35f79312203fcb533ad27511982

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

LOG: [Clang][Lex] Extend HeaderSearch::LookupFile to control OpenFile behavior.

In the case of static compilation the file system is pretty much read-only
and taking a snapshot of it usually is sufficient. In the interactive C++
case the compilation is longer and people can create and include files, etc.
In that case we often do not want to open files or cache failures unless is
absolutely necessary.

This patch extends the original API call by forwarding some optional flags,
so we can continue use it in the previous way with no breakage.
Signed-off-by: Jun Zhang 

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

Added: 


Modified: 
clang/include/clang/Lex/DirectoryLookup.h
clang/include/clang/Lex/HeaderSearch.h
clang/include/clang/Lex/Preprocessor.h
clang/lib/Lex/HeaderSearch.cpp
clang/lib/Lex/PPDirectives.cpp

Removed: 




diff  --git a/clang/include/clang/Lex/DirectoryLookup.h 
b/clang/include/clang/Lex/DirectoryLookup.h
index 3602662029a48..d43b105606f79 100644
--- a/clang/include/clang/Lex/DirectoryLookup.h
+++ b/clang/include/clang/Lex/DirectoryLookup.h
@@ -186,7 +186,8 @@ class DirectoryLookup {
  SmallVectorImpl *RelativePath, Module *RequestingModule,
  ModuleMap::KnownHeader *SuggestedModule,
  bool , bool ,
- bool , SmallVectorImpl ) const;
+ bool , SmallVectorImpl ,
+ bool OpenFile = true) const;
 
 private:
   Optional DoFrameworkLookup(

diff  --git a/clang/include/clang/Lex/HeaderSearch.h 
b/clang/include/clang/Lex/HeaderSearch.h
index 1b7eda333b6bd..e438385f25508 100644
--- a/clang/include/clang/Lex/HeaderSearch.h
+++ b/clang/include/clang/Lex/HeaderSearch.h
@@ -474,7 +474,8 @@ class HeaderSearch {
   SmallVectorImpl *SearchPath, SmallVectorImpl *RelativePath,
   Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule,
   bool *IsMapped, bool *IsFrameworkFound, bool SkipCache = false,
-  bool BuildSystemModule = false);
+  bool BuildSystemModule = false, bool OpenFile = true,
+  bool CacheFailures = true);
 
   /// Look up a subframework for the specified \#include file.
   ///
@@ -759,7 +760,8 @@ class HeaderSearch {
   getFileAndSuggestModule(StringRef FileName, SourceLocation IncludeLoc,
   const DirectoryEntry *Dir, bool IsSystemHeaderDir,
   Module *RequestingModule,
-  ModuleMap::KnownHeader *SuggestedModule);
+  ModuleMap::KnownHeader *SuggestedModule,
+  bool OpenFile = true, bool CacheFailures = true);
 
   /// Cache the result of a successful lookup at the given include location
   /// using the search path at \c HitIt.

diff  --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index 79454b5addead..6e2517632717f 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -2228,7 +2228,8 @@ class Preprocessor {
  ConstSearchDirIterator *CurDir, SmallVectorImpl *SearchPath,
  SmallVectorImpl *RelativePath,
  ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped,
- bool *IsFrameworkFound, bool SkipCache = false);
+ bool *IsFrameworkFound, bool SkipCache = false,
+ bool OpenFile = true, bool CacheFailures = true);
 
   /// Return true if we're in the top-level file, not in a \#include.
   bool isInPrimaryFile() const;

diff  --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp
index 60fd42bc1127a..219c62663ebd0 100644
--- a/clang/lib/Lex/HeaderSearch.cpp
+++ b/clang/lib/Lex/HeaderSearch.cpp
@@ -398,10 +398,11 @@ StringRef DirectoryLookup::getName() const {
 Optional HeaderSearch::getFileAndSuggestModule(
 StringRef FileName, SourceLocation IncludeLoc, const DirectoryEntry *Dir,
 bool IsSystemHeaderDir, Module *RequestingModule,
-ModuleMap::KnownHeader *SuggestedModule) {
+ModuleMap::KnownHeader *SuggestedModule, bool OpenFile /*=true*/,
+bool CacheFailures /*=true*/) {
   // If we have a module map that might map this header, load it and
   // check whether we'll have a suggestion for a module.
-  auto File = getFileMgr().getFileRef(FileName, /*OpenFile=*/true);
+  auto File = getFileMgr().getFileRef(FileName, OpenFile, CacheFailures);
   if (!File) {
 // For rare, surprising errors (e.g. "out of file handles"), diag the EC
 // message.
@@ -431,7 +432,8 @@ Optional DirectoryLookup::LookupFile(
 SmallVectorImpl *SearchPath, SmallVectorImpl *RelativePath,

[clang] 9caee57 - [clang-repl] Fix incorrect return code

2022-07-31 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-07-31T19:07:05+08:00
New Revision: 9caee577ef0f97242a233174be8a980bc4d5446e

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

LOG: [clang-repl] Fix incorrect return code

Without this patch, clang-repl incorrectly pass some tests when there's
error occured.

Signed-off-by: Jun Zhang 

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

Added: 
clang/test/Interpreter/fail.cpp

Modified: 
clang/tools/clang-repl/ClangRepl.cpp

Removed: 




diff  --git a/clang/test/Interpreter/fail.cpp b/clang/test/Interpreter/fail.cpp
new file mode 100644
index 0..1f02dc425ece2
--- /dev/null
+++ b/clang/test/Interpreter/fail.cpp
@@ -0,0 +1,17 @@
+// FIXME: There're some inconsistencies between interactive and non-interactive
+// modes. For example, when clang-repl runs in the interactive mode, issues an
+// error, and then successfully recovers if we decide it's a success then for
+// the non-interactive mode the exit code should be a failure.
+// RUN: clang-repl "int x = 10;" "int y=7; err;" "int y = 10;"
+// RUN: clang-repl "int i = 10;" 'extern "C" int printf(const char*,...);' \
+// RUN:'auto r1 = printf("i = %d\n", i);' | FileCheck 
--check-prefix=CHECK-DRIVER %s
+// REQUIRES: host-supports-jit
+// UNSUPPORTED: system-aix
+// CHECK-DRIVER: i = 10
+// RUN: cat %s | not clang-repl | FileCheck %s
+BOOM!
+extern "C" int printf(const char *, ...);
+int i = 42;
+auto r1 = printf("i = %d\n", i);
+// CHECK: i = 42
+%quit

diff  --git a/clang/tools/clang-repl/ClangRepl.cpp 
b/clang/tools/clang-repl/ClangRepl.cpp
index d3253738c6da1..8f661a57e9906 100644
--- a/clang/tools/clang-repl/ClangRepl.cpp
+++ b/clang/tools/clang-repl/ClangRepl.cpp
@@ -50,7 +50,7 @@ static void LLVMErrorHandler(void *UserData, const char 
*Message,
 
 // If we are running with -verify a reported has to be returned as unsuccess.
 // This is relevant especially for the test suite.
-static int checkDiagErrors(const clang::CompilerInstance *CI) {
+static int checkDiagErrors(const clang::CompilerInstance *CI, bool HasError) {
   unsigned Errs = CI->getDiagnostics().getClient()->getNumErrors();
   if (CI->getDiagnosticOpts().VerifyDiagnostics) {
 // If there was an error that came from the verifier we must return 1 as
@@ -62,7 +62,7 @@ static int checkDiagErrors(const clang::CompilerInstance *CI) 
{
 // The interpreter expects BeginSourceFile/EndSourceFiles to be balanced.
 Client->BeginSourceFile(CI->getLangOpts(), >getPreprocessor());
   }
-  return Errs ? EXIT_FAILURE : EXIT_SUCCESS;
+  return (Errs || HasError) ? EXIT_FAILURE : EXIT_SUCCESS;
 }
 
 llvm::ExitOnError ExitOnErr;
@@ -107,6 +107,8 @@ int main(int argc, const char **argv) {
   llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
   }
 
+  bool HasError = false;
+
   if (OptInputs.empty()) {
 llvm::LineEditor LE("clang-repl");
 // FIXME: Add LE.setListCompleter
@@ -114,13 +116,17 @@ int main(int argc, const char **argv) {
   if (*Line == R"(%quit)")
 break;
   if (*Line == R"(%undo)") {
-if (auto Err = Interp->Undo())
+if (auto Err = Interp->Undo()) {
   llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
+  HasError = true;
+}
 continue;
   }
 
-  if (auto Err = Interp->ParseAndExecute(*Line))
+  if (auto Err = Interp->ParseAndExecute(*Line)) {
 llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
+HasError = true;
+  }
 }
   }
 
@@ -129,5 +135,5 @@ int main(int argc, const char **argv) {
   // later errors use the default handling behavior instead.
   llvm::remove_fatal_error_handler();
 
-  return checkDiagErrors(Interp->getCompilerInstance());
+  return checkDiagErrors(Interp->getCompilerInstance(), HasError);
 }



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


[clang] 3da1395 - [CodeGen][NFC] Use isa_and_nonnull instead of explicit check

2022-07-30 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-07-31T13:03:24+08:00
New Revision: 3da13953834eb31b41949e92886f6fb7f3fd63fc

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

LOG: [CodeGen][NFC] Use isa_and_nonnull instead of explicit check

Signed-off-by: Jun Zhang 

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 8940cee37d3e6..579ebba7736da 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3974,7 +3974,7 @@ llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
 // each other bottoming out with the base dtor.  Therefore we emit non-base
 // dtors on usage, even if there is no dtor definition in the TU.
-if (D && isa(D) &&
+if (isa_and_nonnull(D) &&
 getCXXABI().useThunkForDtorVariant(cast(D),
GD.getDtorType()))
   addDeferredDeclToEmit(GD);



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


[clang] 58c9480 - [CodeGen] Consider MangleCtx when move lazy emission States

2022-07-25 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-07-26T12:34:03+08:00
New Revision: 58c94808450d0ec73bed38d1661314c1a3d56e2f

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

LOG: [CodeGen] Consider MangleCtx when move lazy emission States

Also move MangleCtx when moving some lazy emission states in
CodeGenModule. Without this patch clang-repl hits an invalid address
access when passing `-Xcc -O2` flag.

Signed-off-by: Jun Zhang 

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

Added: 


Modified: 
clang/lib/CodeGen/CGCXXABI.h
clang/lib/CodeGen/CodeGenModule.cpp
clang/test/Interpreter/execute.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGCXXABI.h b/clang/lib/CodeGen/CGCXXABI.h
index a46f7f37141f0..0768e6581acb8 100644
--- a/clang/lib/CodeGen/CGCXXABI.h
+++ b/clang/lib/CodeGen/CGCXXABI.h
@@ -41,6 +41,8 @@ struct CatchTypeInfo;
 
 /// Implements C++ ABI-specific code generation functions.
 class CGCXXABI {
+  friend class CodeGenModule;
+
 protected:
   CodeGenModule 
   std::unique_ptr MangleCtx;

diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 101080b6fe132..29713a5d2b3b3 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -7000,4 +7000,6 @@ void CodeGenModule::moveLazyEmissionStates(CodeGenModule 
*NewBuilder) {
  "Still have (unmerged) EmittedDeferredDecls deferred decls");
 
   NewBuilder->EmittedDeferredDecls = std::move(EmittedDeferredDecls);
+
+  NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
 }

diff  --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index f5c70c21ac507..0396ad82e9b36 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -5,6 +5,7 @@
 // UNSUPPORTED: system-aix
 // CHECK-DRIVER: i = 10
 // RUN: cat %s | clang-repl | FileCheck %s
+// RUN: cat %s | clang-repl -Xcc -O2 | FileCheck %s
 extern "C" int printf(const char *, ...);
 int i = 42;
 auto r1 = printf("i = %d\n", i);



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


[clang] 1a3a2ee - [NFC] Move function definition to cpp file

2022-07-22 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-07-23T13:43:42+08:00
New Revision: 1a3a2eec717b6067e29d8a07318257d2d96da238

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

LOG: [NFC] Move function definition to cpp file

Signed-off-by: Jun Zhang 

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/CodeGenModule.h

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index a8b008b11435..101080b6fe13 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -6973,3 +6973,31 @@ void 
CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream ,
 OS << getContext().getCUIDHash();
   }
 }
+
+void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) {
+  assert(DeferredDeclsToEmit.empty() &&
+ "Should have emitted all decls deferred to emit.");
+  assert(NewBuilder->DeferredDecls.empty() &&
+ "Newly created module should not have deferred decls");
+  NewBuilder->DeferredDecls = std::move(DeferredDecls);
+
+  assert(NewBuilder->DeferredVTables.empty() &&
+ "Newly created module should not have deferred vtables");
+  NewBuilder->DeferredVTables = std::move(DeferredVTables);
+
+  assert(NewBuilder->MangledDeclNames.empty() &&
+ "Newly created module should not have mangled decl names");
+  assert(NewBuilder->Manglings.empty() &&
+ "Newly created module should not have manglings");
+  NewBuilder->Manglings = std::move(Manglings);
+
+  assert(WeakRefReferences.empty() && "Not all WeakRefRefs have been applied");
+  NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
+
+  NewBuilder->TBAA = std::move(TBAA);
+
+  assert(NewBuilder->EmittedDeferredDecls.empty() &&
+ "Still have (unmerged) EmittedDeferredDecls deferred decls");
+
+  NewBuilder->EmittedDeferredDecls = std::move(EmittedDeferredDecls);
+}

diff  --git a/clang/lib/CodeGen/CodeGenModule.h 
b/clang/lib/CodeGen/CodeGenModule.h
index aa57dc5a28d2..c939e7a309f5 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -1514,34 +1514,7 @@ class CodeGenModule : public CodeGenTypeCache {
   /// Move some lazily-emitted states to the NewBuilder. This is especially
   /// essential for the incremental parsing environment like Clang Interpreter,
   /// because we'll lose all important information after each repl.
-  void moveLazyEmissionStates(CodeGenModule *NewBuilder) {
-assert(DeferredDeclsToEmit.empty() &&
-   "Should have emitted all decls deferred to emit.");
-assert(NewBuilder->DeferredDecls.empty() &&
-   "Newly created module should not have deferred decls");
-NewBuilder->DeferredDecls = std::move(DeferredDecls);
-
-assert(NewBuilder->DeferredVTables.empty() &&
-   "Newly created module should not have deferred vtables");
-NewBuilder->DeferredVTables = std::move(DeferredVTables);
-
-assert(NewBuilder->MangledDeclNames.empty() &&
-   "Newly created module should not have mangled decl names");
-assert(NewBuilder->Manglings.empty() &&
-   "Newly created module should not have manglings");
-NewBuilder->Manglings = std::move(Manglings);
-
-assert(WeakRefReferences.empty() &&
-   "Not all WeakRefRefs have been applied");
-NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
-
-NewBuilder->TBAA = std::move(TBAA);
-
-assert(NewBuilder->EmittedDeferredDecls.empty() &&
-   "Still have (unmerged) EmittedDeferredDecls deferred decls");
-
-NewBuilder->EmittedDeferredDecls = std::move(EmittedDeferredDecls);
-  }
+  void moveLazyEmissionStates(CodeGenModule *NewBuilder);
 
 private:
   llvm::Constant *GetOrCreateLLVMFunction(



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


[clang] 8082a00 - [CodeGen] Keep track of decls that were deferred and have been emitted.

2022-07-13 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-07-13T20:00:59+08:00
New Revision: 8082a00286380d0dafa05bfe5ddfe6075b9769f9

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

LOG: [CodeGen] Keep track of decls that were deferred and have been emitted.

This patch adds a new field called EmittedDeferredDecls in CodeGenModule
that keeps track of decls that were deferred and have been emitted.

The intention of this patch is to solve issues in the incremental c++,
we'll lose info of decls that are lazily emitted when we undo their
usage.

See example below:

clang-repl> inline int foo() { return 42;}
clang-repl> int bar = foo();
clang-repl> %undo
clang-repl> int baz = foo();
JIT session error: Symbols not found: [ _Z3foov ]
error: Failed to materialize symbols: { (main, { baz, $.incr_module_2.inits.0,
orc_init_func.incr_module_2 }) }

Signed-off-by: Jun Zhang 

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

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/CodeGenModule.h
clang/test/Interpreter/code-undo.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index a6d58aeef11bd..f832a067237eb 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -445,6 +445,7 @@ void CodeGenModule::checkAliases() {
 
 void CodeGenModule::clear() {
   DeferredDeclsToEmit.clear();
+  EmittedDeferredDecls.clear();
   if (OpenMPRuntime)
 OpenMPRuntime->clear();
 }
@@ -510,6 +511,9 @@ static void setVisibilityFromDLLStorageClass(const 
clang::LangOptions ,
 
 void CodeGenModule::Release() {
   EmitDeferred();
+  DeferredDecls.insert(EmittedDeferredDecls.begin(),
+   EmittedDeferredDecls.end());
+  EmittedDeferredDecls.clear();
   EmitVTablesOpportunistically();
   applyGlobalValReplacements();
   applyReplacements();

diff  --git a/clang/lib/CodeGen/CodeGenModule.h 
b/clang/lib/CodeGen/CodeGenModule.h
index da43b9616c88e..10b49da27dab7 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -344,6 +344,20 @@ class CodeGenModule : public CodeGenTypeCache {
   std::vector DeferredDeclsToEmit;
   void addDeferredDeclToEmit(GlobalDecl GD) {
 DeferredDeclsToEmit.emplace_back(GD);
+addEmittedDeferredDecl(GD);
+  }
+
+  /// Decls that were DeferredDecls and have now been emitted.
+  llvm::DenseMap EmittedDeferredDecls;
+
+  void addEmittedDeferredDecl(GlobalDecl GD) {
+if (!llvm::isa(GD.getDecl()))
+  return;
+llvm::GlobalVariable::LinkageTypes L = getFunctionLinkage(GD);
+if (llvm::GlobalValue::isLinkOnceLinkage(L) ||
+llvm::GlobalValue::isWeakLinkage(L)) {
+  EmittedDeferredDecls[getMangledName(GD)] = GD;
+}
   }
 
   /// List of alias we have emitted. Used to make sure that what they point to
@@ -1516,6 +1530,11 @@ class CodeGenModule : public CodeGenTypeCache {
 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
 
 NewBuilder->TBAA = std::move(TBAA);
+
+assert(NewBuilder->EmittedDeferredDecls.empty() &&
+   "Still have (unmerged) EmittedDeferredDecls deferred decls");
+
+NewBuilder->EmittedDeferredDecls = std::move(EmittedDeferredDecls);
   }
 
 private:

diff  --git a/clang/test/Interpreter/code-undo.cpp 
b/clang/test/Interpreter/code-undo.cpp
index d825460f3b4a4..9a908d6b7e455 100644
--- a/clang/test/Interpreter/code-undo.cpp
+++ b/clang/test/Interpreter/code-undo.cpp
@@ -20,4 +20,9 @@ int foo() { return 2; }
 auto r3 = printf("foo() = %d\n", foo());
 // CHECK-NEXT: foo() = 2
 
+inline int bar() { return 42;}
+auto r4 = bar();
+%undo
+auto r5 = bar();
+
 %quit



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


[clang] eee6a12 - [clang-repl][NFC] Split weak symbol test to a new test

2022-07-07 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-07-08T09:17:11+08:00
New Revision: eee6a12227a608e4c9aa4d9428d3fe55071f2d64

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

LOG: [clang-repl][NFC] Split weak symbol test to a new test

Windows has some issues when we try to use `__attribute__((weak))` in
JIT, so we disabled that. But it's not worth to disable the whole test
just for this single feature. This patch split that part from the
original test so we can keep testing stuff that normally working in
Windows.

Signed-off-by: Jun Zhang 

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

Added: 
clang/test/Interpreter/execute-weak.cpp

Modified: 
clang/test/Interpreter/execute.cpp

Removed: 




diff  --git a/clang/test/Interpreter/execute-weak.cpp 
b/clang/test/Interpreter/execute-weak.cpp
new file mode 100644
index 0..e4577e3ced6e9
--- /dev/null
+++ b/clang/test/Interpreter/execute-weak.cpp
@@ -0,0 +1,14 @@
+// RUN: clang-repl "int x = 10;" "int y=7; err;" "int y = 10;"
+// RUN: clang-repl "int i = 10;" 'extern "C" int printf(const char*,...);' \
+// RUN:'auto r1 = printf("i = %d\n", i);' | FileCheck 
--check-prefix=CHECK-DRIVER %s
+// REQUIRES: host-supports-jit
+// UNSUPPORTED: system-aix
+// XFAIL: system-windows
+// CHECK-DRIVER: i = 10
+// RUN: cat %s | clang-repl | FileCheck %s
+extern "C" int printf(const char *, ...);
+int __attribute__((weak)) bar() { return 42; }
+auto r4 = printf("bar() = %d\n", bar());
+// CHECK: bar() = 42
+
+%quit

diff  --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index b5dad4722c0ba..f5c70c21ac507 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -3,7 +3,6 @@
 // RUN:'auto r1 = printf("i = %d\n", i);' | FileCheck 
--check-prefix=CHECK-DRIVER %s
 // REQUIRES: host-supports-jit
 // UNSUPPORTED: system-aix
-// XFAIL: system-windows
 // CHECK-DRIVER: i = 10
 // RUN: cat %s | clang-repl | FileCheck %s
 extern "C" int printf(const char *, ...);
@@ -19,8 +18,4 @@ auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, 
reinterpret_casthttps://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] bc36618 - Correct XFAIL according to bot owner's advice

2022-07-05 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-07-05T18:46:59+08:00
New Revision: bc366183a5928d7a7d5fd9d6971f43ff1358

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

LOG: Correct XFAIL according to bot owner's advice

Signed-off-by: Jun Zhang 

Added: 


Modified: 
clang/test/Interpreter/execute.cpp

Removed: 




diff  --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index 734127ea8eef..b5dad4722c0b 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -3,7 +3,7 @@
 // RUN:'auto r1 = printf("i = %d\n", i);' | FileCheck 
--check-prefix=CHECK-DRIVER %s
 // REQUIRES: host-supports-jit
 // UNSUPPORTED: system-aix
-// XFAIL: windows-msvc || ps4
+// XFAIL: system-windows
 // CHECK-DRIVER: i = 10
 // RUN: cat %s | clang-repl | FileCheck %s
 extern "C" int printf(const char *, ...);



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


[clang] f03b876 - Reland "Reland "[NFC] Add a missing test for for clang-repl""

2022-07-05 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-07-05T18:23:26+08:00
New Revision: f03b876e7e9567ee71ee66f8f194918aac37d5fa

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

LOG: Reland "Reland "[NFC] Add a missing test for for clang-repl""

This reverts commit 6956840b5c0029d7f8e043b3c77bb1ffc230e4d5.
Try to use `XFAIL: windows-msvc || ps4` to disable all unsupported targets.

Signed-off-by: Jun Zhang 

Added: 


Modified: 
clang/test/Interpreter/execute.cpp

Removed: 




diff  --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index f5c70c21ac507..734127ea8eef6 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -3,6 +3,7 @@
 // RUN:'auto r1 = printf("i = %d\n", i);' | FileCheck 
--check-prefix=CHECK-DRIVER %s
 // REQUIRES: host-supports-jit
 // UNSUPPORTED: system-aix
+// XFAIL: windows-msvc || ps4
 // CHECK-DRIVER: i = 10
 // RUN: cat %s | clang-repl | FileCheck %s
 extern "C" int printf(const char *, ...);
@@ -18,4 +19,8 @@ auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, 
reinterpret_casthttps://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 6956840 - Revert "Reland "[NFC] Add a missing test for for clang-repl""

2022-07-03 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-07-03T19:42:39+08:00
New Revision: 6956840b5c0029d7f8e043b3c77bb1ffc230e4d5

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

LOG: Revert "Reland "[NFC] Add a missing test for for clang-repl""

This reverts commit 8679cbc29fb76195544956fe233060bb7a1a6453.
See https://lab.llvm.org/buildbot/#/builders/216/builds/6799

Added: 


Modified: 
clang/test/Interpreter/execute.cpp

Removed: 




diff  --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index 3754e8d9f964..f5c70c21ac50 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -3,7 +3,6 @@
 // RUN:'auto r1 = printf("i = %d\n", i);' | FileCheck 
--check-prefix=CHECK-DRIVER %s
 // REQUIRES: host-supports-jit
 // UNSUPPORTED: system-aix
-// XFAIL: windows-msvc
 // CHECK-DRIVER: i = 10
 // RUN: cat %s | clang-repl | FileCheck %s
 extern "C" int printf(const char *, ...);
@@ -19,8 +18,4 @@ auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, 
reinterpret_casthttps://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 8679cbc - Reland "[NFC] Add a missing test for for clang-repl"

2022-07-03 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-07-03T19:15:59+08:00
New Revision: 8679cbc29fb76195544956fe233060bb7a1a6453

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

LOG: Reland "[NFC] Add a missing test for for clang-repl"

This reverts 3668d1264e2d246f7e222338b8a5cab18ce1bdab
As far as we know, `__attribute__((weak))` support has been really bad
in runtimeldyld, so we just disable it in Windows at this moment. This
should fix the angry Windows buildbot.

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

Added: 


Modified: 
clang/test/Interpreter/execute.cpp

Removed: 




diff  --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index f5c70c21ac50..3754e8d9f964 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -3,6 +3,7 @@
 // RUN:'auto r1 = printf("i = %d\n", i);' | FileCheck 
--check-prefix=CHECK-DRIVER %s
 // REQUIRES: host-supports-jit
 // UNSUPPORTED: system-aix
+// XFAIL: windows-msvc
 // CHECK-DRIVER: i = 10
 // RUN: cat %s | clang-repl | FileCheck %s
 extern "C" int printf(const char *, ...);
@@ -18,4 +19,8 @@ auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, 
reinterpret_casthttps://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 3668d12 - Revert "[NFC] Add a missing test for for clang-repl"

2022-07-01 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-07-01T23:55:55+08:00
New Revision: 3668d1264e2d246f7e222338b8a5cab18ce1bdab

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

LOG: Revert "[NFC] Add a missing test for for clang-repl"

This reverts commit 2750985a5ccb97f4630c3443e75d78ed435d2bd0.
This has caused Windows buildbot unhappy :(

Added: 


Modified: 
clang/test/Interpreter/execute.cpp

Removed: 




diff  --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index 8fb528c4750a8..f5c70c21ac507 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -18,8 +18,4 @@ auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, 
reinterpret_casthttps://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2750985 - [NFC] Add a missing test for for clang-repl

2022-07-01 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-07-01T23:26:54+08:00
New Revision: 2750985a5ccb97f4630c3443e75d78ed435d2bd0

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

LOG: [NFC] Add a missing test for for clang-repl

This adds a missing test for 0ecbedc0986bd4b7b90a60a5f31d32337160d4c4
Signed-off-by: Jun Zhang 

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

Added: 


Modified: 
clang/test/Interpreter/execute.cpp

Removed: 




diff  --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index f5c70c21ac507..8fb528c4750a8 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -18,4 +18,8 @@ auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, 
reinterpret_casthttps://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] dea5a9c - [clang-repl] Implement code undo.

2022-06-26 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-06-26T18:32:18+08:00
New Revision: dea5a9cc929048be261a4c030407e4d7e1e70fec

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

LOG: [clang-repl] Implement code undo.

In interactive C++ it is convenient to roll back to a previous state of the
compiler. For example:
clang-repl> int x = 42;
clang-repl> %undo
clang-repl> float x = 24 // not an error

To support this, the patch extends the functionality used to recover from
errors and adds functionality to recover the low-level execution infrastructure.

The current implementation is based on watermarks. It exploits the fact that
at each incremental input the underlying compiler infrastructure is in a valid
state. We can only go N incremental inputs back to a previous valid state. We do
not need and do not do any further dependency tracking.

This patch was co-developed with V. Vassilev, relies on the past work of Purva
Chaudhari in clang-repl and is inspired by the past work on the same feature
in the Cling interpreter.

Co-authored-by: Purva-Chaudhari 
Co-authored-by: Vassil Vassilev 
Signed-off-by: Jun Zhang 

Added: 
clang/test/Interpreter/code-undo.cpp

Modified: 
clang/include/clang/Interpreter/Interpreter.h
clang/lib/Interpreter/IncrementalExecutor.cpp
clang/lib/Interpreter/IncrementalExecutor.h
clang/lib/Interpreter/IncrementalParser.cpp
clang/lib/Interpreter/IncrementalParser.h
clang/lib/Interpreter/Interpreter.cpp
clang/test/Interpreter/execute.cpp
clang/test/Interpreter/plugins.cpp
clang/test/Interpreter/sanity.c
clang/tools/clang-repl/ClangRepl.cpp
clang/unittests/Interpreter/InterpreterTest.cpp

Removed: 




diff  --git a/clang/include/clang/Interpreter/Interpreter.h 
b/clang/include/clang/Interpreter/Interpreter.h
index f2fdb90f5ba48..fd22af9766135 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -69,6 +69,9 @@ class Interpreter {
 return llvm::Error::success();
   }
 
+  /// Undo N previous incremental inputs.
+  llvm::Error Undo(unsigned N = 1);
+
   /// \returns the \c JITTargetAddress of a \c GlobalDecl. This interface uses
   /// the CodeGenModule's internal mangling cache to avoid recomputing the
   /// mangled name.

diff  --git a/clang/lib/Interpreter/IncrementalExecutor.cpp 
b/clang/lib/Interpreter/IncrementalExecutor.cpp
index c5ed9b0fb4571..2445ba906a4c2 100644
--- a/clang/lib/Interpreter/IncrementalExecutor.cpp
+++ b/clang/lib/Interpreter/IncrementalExecutor.cpp
@@ -12,6 +12,7 @@
 
 #include "IncrementalExecutor.h"
 
+#include "clang/Interpreter/PartialTranslationUnit.h"
 #include "llvm/ExecutionEngine/ExecutionEngine.h"
 #include "llvm/ExecutionEngine/Orc/CompileUtils.h"
 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
@@ -58,8 +59,24 @@ llvm::Error IncrementalExecutor::cleanUp() {
   return Jit->deinitialize(Jit->getMainJITDylib());
 }
 
-llvm::Error IncrementalExecutor::addModule(std::unique_ptr M) {
-  return Jit->addIRModule(llvm::orc::ThreadSafeModule(std::move(M), TSCtx));
+llvm::Error IncrementalExecutor::addModule(PartialTranslationUnit ) {
+  llvm::orc::ResourceTrackerSP RT =
+  Jit->getMainJITDylib().createResourceTracker();
+  ResourceTrackers[] = RT;
+
+  return Jit->addIRModule(RT, {std::move(PTU.TheModule), TSCtx});
+}
+
+llvm::Error IncrementalExecutor::removeModule(PartialTranslationUnit ) {
+
+  llvm::orc::ResourceTrackerSP RT = std::move(ResourceTrackers[]);
+  if (!RT)
+return llvm::Error::success();
+
+  ResourceTrackers.erase();
+  if (llvm::Error Err = RT->remove())
+return Err;
+  return llvm::Error::success();
 }
 
 llvm::Error IncrementalExecutor::runCtors() const {

diff  --git a/clang/lib/Interpreter/IncrementalExecutor.h 
b/clang/lib/Interpreter/IncrementalExecutor.h
index 75c181d76302a..fd93b1d390357 100644
--- a/clang/lib/Interpreter/IncrementalExecutor.h
+++ b/clang/lib/Interpreter/IncrementalExecutor.h
@@ -13,6 +13,7 @@
 #ifndef LLVM_CLANG_LIB_INTERPRETER_INCREMENTALEXECUTOR_H
 #define LLVM_CLANG_LIB_INTERPRETER_INCREMENTALEXECUTOR_H
 
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
@@ -29,11 +30,17 @@ class ThreadSafeContext;
 } // namespace llvm
 
 namespace clang {
+
+struct PartialTranslationUnit;
+
 class IncrementalExecutor {
   using CtorDtorIterator = llvm::orc::CtorDtorIterator;
   std::unique_ptr Jit;
   llvm::orc::ThreadSafeContext 
 
+  llvm::DenseMap
+  ResourceTrackers;
+
 public:
   enum SymbolNameKind { IRName, LinkerName };
 
@@ -41,7 +48,8 @@ class IncrementalExecutor {
   const llvm::Triple );
   ~IncrementalExecutor();
 
-  llvm::Error addModule(std::unique_ptr M);
+  

[clang] cd64a42 - Reland "[CodeGen] Keep track info of lazy-emitted symbols in ModuleBuilder"

2022-06-18 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-06-18T20:27:21+08:00
New Revision: cd64a427efa0baaf1bb7ae624d4301908afc07f7

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

LOG: Reland "[CodeGen] Keep track info of lazy-emitted symbols in ModuleBuilder"

This reverts commits:
d3ddc251acae631bf5ab4da13878f7e8b5b5a451
d90eecff5c9e7e9f8263de6cd72d70322400829f

It turned out there're some options turned on that leaks the memory
intentionally, which fires the asan builds after the patch being
applied. The issue has been fixed in
7bc00ce5cd41aad5fd0775f58c8e85a0a8d9ee56, so reland it.

Below is the original commit message:

The intent of this patch is to selectively carry some states over to
the Builder so we won't lose the information of the previous symbols.

This used to be several downstream patches of Cling, it aims to fix
errors in Clang Interpreter when trying to use inline functions.
Before this patch:

clang-repl> inline int foo() { return 42;}
clang-repl> int x = foo();

JIT session error: Symbols not found: [ _Z3foov ]
error: Failed to materialize symbols:
{ (main, { x, $.incr_module_1.__inits.0, __orc_init_func.incr_module_1 }) }

Co-authored-by: Axel Naumann 
Signed-off-by: Jun Zhang 

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.h
clang/lib/CodeGen/ModuleBuilder.cpp
clang/test/Interpreter/execute.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.h 
b/clang/lib/CodeGen/CodeGenModule.h
index f5ae83a2faca9..79e9a462a3d72 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -1486,6 +1486,33 @@ class CodeGenModule : public CodeGenTypeCache {
   void printPostfixForExternalizedDecl(llvm::raw_ostream ,
const Decl *D) const;
 
+  /// Move some lazily-emitted states to the NewBuilder. This is especially
+  /// essential for the incremental parsing environment like Clang Interpreter,
+  /// because we'll lose all important information after each repl.
+  void moveLazyEmissionStates(CodeGenModule *NewBuilder) {
+assert(DeferredDeclsToEmit.empty() &&
+   "Should have emitted all decls deferred to emit.");
+assert(NewBuilder->DeferredDecls.empty() &&
+   "Newly created module should not have deferred decls");
+NewBuilder->DeferredDecls = std::move(DeferredDecls);
+
+assert(NewBuilder->DeferredVTables.empty() &&
+   "Newly created module should not have deferred vtables");
+NewBuilder->DeferredVTables = std::move(DeferredVTables);
+
+assert(NewBuilder->MangledDeclNames.empty() &&
+   "Newly created module should not have mangled decl names");
+assert(NewBuilder->Manglings.empty() &&
+   "Newly created module should not have manglings");
+NewBuilder->Manglings = std::move(Manglings);
+
+assert(WeakRefReferences.empty() &&
+   "Not all WeakRefRefs have been applied");
+NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
+
+NewBuilder->TBAA = std::move(TBAA);
+  }
+
 private:
   llvm::Constant *GetOrCreateLLVMFunction(
   StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,

diff  --git a/clang/lib/CodeGen/ModuleBuilder.cpp 
b/clang/lib/CodeGen/ModuleBuilder.cpp
index 50b7fd8eb993c..8e97a298ce7fa 100644
--- a/clang/lib/CodeGen/ModuleBuilder.cpp
+++ b/clang/lib/CodeGen/ModuleBuilder.cpp
@@ -134,7 +134,14 @@ namespace {
   llvm::LLVMContext ) {
   assert(!M && "Replacing existing Module?");
   M.reset(new llvm::Module(ExpandModuleName(ModuleName, CodeGenOpts), C));
+
+  std::unique_ptr OldBuilder = std::move(Builder);
+
   Initialize(*Ctx);
+
+  if (OldBuilder)
+OldBuilder->moveLazyEmissionStates(Builder.get());
+
   return M.get();
 }
 

diff  --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index 298046c068c37..61e68990acf96 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -13,4 +13,8 @@ struct S { float f = 1.0; S *m = nullptr;} s;
 
 auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, reinterpret_cast(s.m));
 // CHECK-NEXT: S[f=1.00, m=0x0]
+
+inline int foo() { return 42; }
+int r3 = foo();
+
 quit



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


[clang] 44f0a26 - Revert "Reland "[CodeGen] Keep track info of lazy-emitted symbols in ModuleBuilder""

2022-06-14 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-06-14T19:53:17+08:00
New Revision: 44f0a2658d22ffc12bac6ca2c8f4a3d98603ea3a

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

LOG: Revert "Reland "[CodeGen] Keep track info of lazy-emitted symbols in 
ModuleBuilder""

This reverts commit 781ee538da1855876b085989a37ec959e3f2ecd1.

Asan build is still broken :(

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.h
clang/lib/CodeGen/ModuleBuilder.cpp
clang/test/Interpreter/execute.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.h 
b/clang/lib/CodeGen/CodeGenModule.h
index cce8e46ad5ac6..779d94ad62d98 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -1486,33 +1486,6 @@ class CodeGenModule : public CodeGenTypeCache {
   void printPostfixForExternalizedDecl(llvm::raw_ostream ,
const Decl *D) const;
 
-  /// Move some lazily-emitted states to the NewBuilder. This is especially
-  /// essential for the incremental parsing environment like Clang Interpreter,
-  /// because we'll lose all important information after each repl.
-  void moveLazyEmissionStates(CodeGenModule *NewBuilder) {
-assert(DeferredDeclsToEmit.empty() &&
-   "Should have emitted all decls deferred to emit.");
-assert(NewBuilder->DeferredDecls.empty() &&
-   "Newly created module should not have deferred decls");
-std::swap(NewBuilder->DeferredDecls, DeferredDecls);
-
-assert(NewBuilder->DeferredVTables.empty() &&
-   "Newly created module should not have deferred vtables");
-std::swap(NewBuilder->DeferredVTables, DeferredVTables);
-
-assert(NewBuilder->MangledDeclNames.empty() &&
-   "Newly created module should not have mangled decl names");
-assert(NewBuilder->Manglings.empty() &&
-   "Newly created module should not have manglings");
-std::swap(NewBuilder->Manglings, Manglings);
-
-assert(WeakRefReferences.empty() &&
-   "Not all WeakRefRefs have been applied");
-std::swap(NewBuilder->WeakRefReferences, WeakRefReferences);
-
-std::swap(NewBuilder->TBAA, TBAA);
-  }
-
 private:
   llvm::Constant *GetOrCreateLLVMFunction(
   StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,

diff  --git a/clang/lib/CodeGen/ModuleBuilder.cpp 
b/clang/lib/CodeGen/ModuleBuilder.cpp
index 8e97a298ce7fa..50b7fd8eb993c 100644
--- a/clang/lib/CodeGen/ModuleBuilder.cpp
+++ b/clang/lib/CodeGen/ModuleBuilder.cpp
@@ -134,14 +134,7 @@ namespace {
   llvm::LLVMContext ) {
   assert(!M && "Replacing existing Module?");
   M.reset(new llvm::Module(ExpandModuleName(ModuleName, CodeGenOpts), C));
-
-  std::unique_ptr OldBuilder = std::move(Builder);
-
   Initialize(*Ctx);
-
-  if (OldBuilder)
-OldBuilder->moveLazyEmissionStates(Builder.get());
-
   return M.get();
 }
 

diff  --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index 61e68990acf96..298046c068c37 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -13,8 +13,4 @@ struct S { float f = 1.0; S *m = nullptr;} s;
 
 auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, reinterpret_cast(s.m));
 // CHECK-NEXT: S[f=1.00, m=0x0]
-
-inline int foo() { return 42; }
-int r3 = foo();
-
 quit



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


[clang] 781ee53 - Reland "[CodeGen] Keep track info of lazy-emitted symbols in ModuleBuilder"

2022-06-14 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-06-14T18:36:03+08:00
New Revision: 781ee538da1855876b085989a37ec959e3f2ecd1

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

LOG: Reland "[CodeGen] Keep track info of lazy-emitted symbols in ModuleBuilder"

This reverts commits:
d3ddc251acae631bf5ab4da13878f7e8b5b5a451
d90eecff5c9e7e9f8263de6cd72d70322400829f

This relands below commit with asan fix:

The intent of this patch is to selectively carry some states over to
the Builder so we won't lose the information of the previous symbols.

This used to be several downstream patches of Cling, it aims to fix
errors in Clang Interpreter when trying to use inline functions.
Before this patch:

clang-repl> inline int foo() { return 42;}
clang-repl> int x = foo();

JIT session error: Symbols not found: [ _Z3foov ]
error: Failed to materialize symbols:
{ (main, { x, $.incr_module_1.__inits.0, __orc_init_func.incr_module_1 }) }

Co-authored-by: Axel Naumann 
Signed-off-by: Jun Zhang 

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

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.h
clang/lib/CodeGen/ModuleBuilder.cpp
clang/test/Interpreter/execute.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.h 
b/clang/lib/CodeGen/CodeGenModule.h
index 779d94ad62d98..cce8e46ad5ac6 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -1486,6 +1486,33 @@ class CodeGenModule : public CodeGenTypeCache {
   void printPostfixForExternalizedDecl(llvm::raw_ostream ,
const Decl *D) const;
 
+  /// Move some lazily-emitted states to the NewBuilder. This is especially
+  /// essential for the incremental parsing environment like Clang Interpreter,
+  /// because we'll lose all important information after each repl.
+  void moveLazyEmissionStates(CodeGenModule *NewBuilder) {
+assert(DeferredDeclsToEmit.empty() &&
+   "Should have emitted all decls deferred to emit.");
+assert(NewBuilder->DeferredDecls.empty() &&
+   "Newly created module should not have deferred decls");
+std::swap(NewBuilder->DeferredDecls, DeferredDecls);
+
+assert(NewBuilder->DeferredVTables.empty() &&
+   "Newly created module should not have deferred vtables");
+std::swap(NewBuilder->DeferredVTables, DeferredVTables);
+
+assert(NewBuilder->MangledDeclNames.empty() &&
+   "Newly created module should not have mangled decl names");
+assert(NewBuilder->Manglings.empty() &&
+   "Newly created module should not have manglings");
+std::swap(NewBuilder->Manglings, Manglings);
+
+assert(WeakRefReferences.empty() &&
+   "Not all WeakRefRefs have been applied");
+std::swap(NewBuilder->WeakRefReferences, WeakRefReferences);
+
+std::swap(NewBuilder->TBAA, TBAA);
+  }
+
 private:
   llvm::Constant *GetOrCreateLLVMFunction(
   StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,

diff  --git a/clang/lib/CodeGen/ModuleBuilder.cpp 
b/clang/lib/CodeGen/ModuleBuilder.cpp
index 50b7fd8eb993c..8e97a298ce7fa 100644
--- a/clang/lib/CodeGen/ModuleBuilder.cpp
+++ b/clang/lib/CodeGen/ModuleBuilder.cpp
@@ -134,7 +134,14 @@ namespace {
   llvm::LLVMContext ) {
   assert(!M && "Replacing existing Module?");
   M.reset(new llvm::Module(ExpandModuleName(ModuleName, CodeGenOpts), C));
+
+  std::unique_ptr OldBuilder = std::move(Builder);
+
   Initialize(*Ctx);
+
+  if (OldBuilder)
+OldBuilder->moveLazyEmissionStates(Builder.get());
+
   return M.get();
 }
 

diff  --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index 298046c068c37..61e68990acf96 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -13,4 +13,8 @@ struct S { float f = 1.0; S *m = nullptr;} s;
 
 auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, reinterpret_cast(s.m));
 // CHECK-NEXT: S[f=1.00, m=0x0]
+
+inline int foo() { return 42; }
+int r3 = foo();
+
 quit



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


[clang] 0ecbedc - Also move WeakRefReferences in CodeGenModule::moveLazyEmssionStates

2022-06-09 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-06-10T13:11:09+08:00
New Revision: 0ecbedc0986bd4b7b90a60a5f31d32337160d4c4

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

LOG: Also move WeakRefReferences in CodeGenModule::moveLazyEmssionStates

I forgot this field in b8f9459715815fa055b3e1c5f970c616797dfcfb
Signed-off-by: Jun Zhang 

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.h

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.h 
b/clang/lib/CodeGen/CodeGenModule.h
index b7c180f1c8859..1eaeeb880597e 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -1499,6 +1499,8 @@ class CodeGenModule : public CodeGenTypeCache {
 
 assert(WeakRefReferences.empty() &&
"Not all WeakRefRefs have been applied");
+NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
+
 NewBuilder->TBAA = std::move(TBAA);
   }
 



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


[clang] b8f9459 - [CodeGen] Keep track info of lazy-emitted symbols in ModuleBuilder

2022-06-09 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-06-09T23:12:21+08:00
New Revision: b8f9459715815fa055b3e1c5f970c616797dfcfb

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

LOG: [CodeGen] Keep track info of lazy-emitted symbols in ModuleBuilder

The intent of this patch is to selectively carry some states over to
the Builder so we won't lose the information of the previous symbols.

This used to be several downstream patches of Cling, it aims to fix
errors in Clang Interpreter when trying to use inline functions.
Before this patch:

clang-repl> inline int foo() { return 42;}
clang-repl> int x = foo();

JIT session error: Symbols not found: [ _Z3foov ]
error: Failed to materialize symbols:
{ (main, { x, $.incr_module_1.__inits.0, __orc_init_func.incr_module_1 }) }

Co-authored-by: Axel Naumann 
Signed-off-by: Jun Zhang 

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

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.h
clang/lib/CodeGen/ModuleBuilder.cpp
clang/test/Interpreter/execute.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.h 
b/clang/lib/CodeGen/CodeGenModule.h
index 0ac476dd6dbcc..b7c180f1c8859 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -1477,6 +1477,31 @@ class CodeGenModule : public CodeGenTypeCache {
   void printPostfixForExternalizedDecl(llvm::raw_ostream ,
const Decl *D) const;
 
+  /// Move some lazily-emitted states to the NewBuilder. This is especially
+  /// essential for the incremental parsing environment like Clang Interpreter,
+  /// because we'll lose all important information after each repl.
+  void moveLazyEmissionStates(CodeGenModule *NewBuilder) {
+assert(DeferredDeclsToEmit.empty() &&
+   "Should have emitted all decls deferred to emit.");
+assert(NewBuilder->DeferredDecls.empty() &&
+   "Newly created module should not have deferred decls");
+NewBuilder->DeferredDecls = std::move(DeferredDecls);
+
+assert(NewBuilder->DeferredVTables.empty() &&
+   "Newly created module should not have deferred vtables");
+NewBuilder->DeferredVTables = std::move(DeferredVTables);
+
+assert(NewBuilder->MangledDeclNames.empty() &&
+   "Newly created module should not have mangled decl names");
+assert(NewBuilder->Manglings.empty() &&
+   "Newly created module should not have manglings");
+NewBuilder->Manglings = std::move(Manglings);
+
+assert(WeakRefReferences.empty() &&
+   "Not all WeakRefRefs have been applied");
+NewBuilder->TBAA = std::move(TBAA);
+  }
+
 private:
   llvm::Constant *GetOrCreateLLVMFunction(
   StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,

diff  --git a/clang/lib/CodeGen/ModuleBuilder.cpp 
b/clang/lib/CodeGen/ModuleBuilder.cpp
index 50b7fd8eb993c..8e97a298ce7fa 100644
--- a/clang/lib/CodeGen/ModuleBuilder.cpp
+++ b/clang/lib/CodeGen/ModuleBuilder.cpp
@@ -134,7 +134,14 @@ namespace {
   llvm::LLVMContext ) {
   assert(!M && "Replacing existing Module?");
   M.reset(new llvm::Module(ExpandModuleName(ModuleName, CodeGenOpts), C));
+
+  std::unique_ptr OldBuilder = std::move(Builder);
+
   Initialize(*Ctx);
+
+  if (OldBuilder)
+OldBuilder->moveLazyEmissionStates(Builder.get());
+
   return M.get();
 }
 

diff  --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index 298046c068c37..61e68990acf96 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -13,4 +13,8 @@ struct S { float f = 1.0; S *m = nullptr;} s;
 
 auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, reinterpret_cast(s.m));
 // CHECK-NEXT: S[f=1.00, m=0x0]
+
+inline int foo() { return 42; }
+int r3 = foo();
+
 quit



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


[clang] 218dcda - [Clang] Use std::move in GlobalModuleIndex::readIndex. NFC

2022-04-26 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-04-26T16:45:01+08:00
New Revision: 218dcdad8a0c0f3340a97dafa24456125fe9b4fb

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

LOG: [Clang] Use std::move in GlobalModuleIndex::readIndex. NFC

BitstreamCursors are heavy-weight objects that should not be passed by value.

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

Added: 


Modified: 
clang/lib/Serialization/GlobalModuleIndex.cpp

Removed: 




diff  --git a/clang/lib/Serialization/GlobalModuleIndex.cpp 
b/clang/lib/Serialization/GlobalModuleIndex.cpp
index 52ce17d984bf4..b2283c2b39877 100644
--- a/clang/lib/Serialization/GlobalModuleIndex.cpp
+++ b/clang/lib/Serialization/GlobalModuleIndex.cpp
@@ -277,7 +277,7 @@ GlobalModuleIndex::readIndex(StringRef Path) {
   return std::make_pair(nullptr, Res.takeError());
   }
 
-  return std::make_pair(new GlobalModuleIndex(std::move(Buffer), Cursor),
+  return std::make_pair(new GlobalModuleIndex(std::move(Buffer), 
std::move(Cursor)),
 llvm::Error::success());
 }
 



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


[clang] e33867a - Fix an issue in comment. NFC

2022-04-24 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-04-25T12:45:39+08:00
New Revision: e33867a43410ea425c169cde9de7187f08264e59

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

LOG: Fix an issue in comment. NFC

I think the author renamed the function but forgot to update the
comment.
Signed-off-by: Jun Zhang 

Added: 


Modified: 
clang/lib/Sema/SemaDecl.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 250a553c414ea..3f095bc61ebe0 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -5794,7 +5794,7 @@ static bool hasSimilarParameters(ASTContext ,
   return true;
 }
 
-/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
+/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
 /// declarator needs to be rebuilt in the current instantiation.
 /// Any bits of declarator which appear before the name are valid for
 /// consideration here.  That's specifically the type in the decl spec



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


[clang] 3b3dd76 - Use range based for loop in Sema::CheckParameterPacksForExpansion. NFC

2022-04-21 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-04-22T13:31:31+08:00
New Revision: 3b3dd76d8da80ff91295d8c0c23de8462ac22b49

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

LOG: Use range based for loop in Sema::CheckParameterPacksForExpansion. NFC

Signed-off-by: Jun Zhang 

Added: 


Modified: 
clang/lib/Sema/SemaTemplateVariadic.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplateVariadic.cpp 
b/clang/lib/Sema/SemaTemplateVariadic.cpp
index 51c79e93ab0a1..790792f77b24f 100644
--- a/clang/lib/Sema/SemaTemplateVariadic.cpp
+++ b/clang/lib/Sema/SemaTemplateVariadic.cpp
@@ -677,21 +677,19 @@ bool Sema::CheckParameterPacksForExpansion(
   Optional NumPartialExpansions;
   SourceLocation PartiallySubstitutedPackLoc;
 
-  for (ArrayRef::iterator i = Unexpanded.begin(),
- end = Unexpanded.end();
-  i != end; ++i) {
+  for (UnexpandedParameterPack ParmPack : Unexpanded) {
 // Compute the depth and index for this parameter pack.
 unsigned Depth = 0, Index = 0;
 IdentifierInfo *Name;
 bool IsVarDeclPack = false;
 
-if (const TemplateTypeParmType *TTP
-= i->first.dyn_cast()) {
+if (const TemplateTypeParmType *TTP =
+ParmPack.first.dyn_cast()) {
   Depth = TTP->getDepth();
   Index = TTP->getIndex();
   Name = TTP->getIdentifier();
 } else {
-  NamedDecl *ND = i->first.get();
+  NamedDecl *ND = ParmPack.first.get();
   if (isa(ND))
 IsVarDeclPack = true;
   else
@@ -706,9 +704,9 @@ bool Sema::CheckParameterPacksForExpansion(
   // Figure out whether we're instantiating to an argument pack or not.
   typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
 
-  llvm::PointerUnion *Instantiation
-= CurrentInstantiationScope->findInstantiationOf(
-i->first.get());
+  llvm::PointerUnion *Instantiation =
+  CurrentInstantiationScope->findInstantiationOf(
+  ParmPack.first.get());
   if (Instantiation->is()) {
 // We could expand this function parameter pack.
 NewPackSize = Instantiation->get()->size();
@@ -745,7 +743,7 @@ bool Sema::CheckParameterPacksForExpansion(
   RetainExpansion = true;
   // We don't actually know the new pack size yet.
   NumPartialExpansions = NewPackSize;
-  PartiallySubstitutedPackLoc = i->second;
+  PartiallySubstitutedPackLoc = ParmPack.second;
   continue;
 }
   }
@@ -756,7 +754,7 @@ bool Sema::CheckParameterPacksForExpansion(
   // Record it.
   NumExpansions = NewPackSize;
   FirstPack.first = Name;
-  FirstPack.second = i->second;
+  FirstPack.second = ParmPack.second;
   HaveFirstPack = true;
   continue;
 }
@@ -767,12 +765,12 @@ bool Sema::CheckParameterPacksForExpansion(
   //   the same number of arguments specified.
   if (HaveFirstPack)
 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
-  << FirstPack.first << Name << *NumExpansions << NewPackSize
-  << SourceRange(FirstPack.second) << SourceRange(i->second);
+<< FirstPack.first << Name << *NumExpansions << NewPackSize
+<< SourceRange(FirstPack.second) << SourceRange(ParmPack.second);
   else
 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
-  << Name << *NumExpansions << NewPackSize
-  << SourceRange(i->second);
+<< Name << *NumExpansions << NewPackSize
+<< SourceRange(ParmPack.second);
   return true;
 }
   }



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


[clang] 9c06937 - Reland "[Clang][Sema] Fix invalid redefinition error in if/switch/for statement"

2022-04-20 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-04-21T01:18:58+08:00
New Revision: 9c069374cebe0162bc4f0b9d0397cf2b1c5febf6

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

LOG: Reland "[Clang][Sema] Fix invalid redefinition error in if/switch/for 
statement"

This reverts commit 9f075c3d84fb359efb6496535ab397a6f09609e2.
The broken build has alreasy been fixed in D124012, so reland it now.
Signed-off-by: Jun Zhang 

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/IdentifierResolver.cpp
clang/test/SemaCXX/cxx1z-init-statement.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 03561fe2150aa..fb81e9db5691e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -119,6 +119,10 @@ Bug Fixes
   This fixes Issue `Issue 52802 
`_.
 - Unknown type attributes with a ``[[]]`` spelling are no longer diagnosed 
twice.
   This fixes Issue `Issue 54817 
`_.
+- Clang should no longer incorrectly diagnose a variable declaration inside of
+  a lambda expression that shares the name of a variable in a containing
+  if/while/for/switch init statement as a redeclaration.
+  This fixes `Issue 54913 
`_.
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/lib/Sema/IdentifierResolver.cpp 
b/clang/lib/Sema/IdentifierResolver.cpp
index cef1ae890e6cb..9081714c893f5 100644
--- a/clang/lib/Sema/IdentifierResolver.cpp
+++ b/clang/lib/Sema/IdentifierResolver.cpp
@@ -123,7 +123,7 @@ bool IdentifierResolver::isDeclInScope(Decl *D, DeclContext 
*Ctx, Scope *S,
   assert(S->getParent() && "No TUScope?");
   // If the current decl is in a lambda, we shouldn't consider this is a
   // redefinition as lambda has its own scope.
-  if (S->getParent()->isControlScope()) {
+  if (S->getParent()->isControlScope() && !S->isFunctionScope()) {
 S = S->getParent();
 if (S->isDeclScope(D))
   return true;

diff  --git a/clang/test/SemaCXX/cxx1z-init-statement.cpp 
b/clang/test/SemaCXX/cxx1z-init-statement.cpp
index eea2589ab7c62..b963c9eabe79b 100644
--- a/clang/test/SemaCXX/cxx1z-init-statement.cpp
+++ b/clang/test/SemaCXX/cxx1z-init-statement.cpp
@@ -90,3 +90,18 @@ void test_constexpr_init_stmt() {
   static_assert(constexpr_switch_init(-2) == 0, "");
   static_assert(constexpr_switch_init(-5) == -1, "");
 }
+
+int test_lambda_init() {
+  if (int x = []() {int x = 42; return x; }(); x) {
+  };
+
+  switch (int y = []() {int y = 42; return y; }(); y) {
+  case 42:
+return 1;
+  }
+
+  for (int x = [] { int x = 0; return x; }();;)
+;
+
+  return 0;
+}



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


[clang] 9f075c3 - Revert "[Clang][Sema] Fix invalid redefinition error in if/switch/for statement"

2022-04-20 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-04-20T23:45:44+08:00
New Revision: 9f075c3d84fb359efb6496535ab397a6f09609e2

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

LOG: Revert "[Clang][Sema] Fix invalid redefinition error in if/switch/for 
statement"

This reverts commit be0905a333d6f7c4d7f5c70c18211463e53473cd.
This patch broke build addressed in 
https://github.com/llvm/llvm-project/issues/54968
Signed-off-by: Jun Zhang 

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/IdentifierResolver.cpp
clang/test/SemaCXX/cxx1z-init-statement.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index fb81e9db5691e..03561fe2150aa 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -119,10 +119,6 @@ Bug Fixes
   This fixes Issue `Issue 52802 
`_.
 - Unknown type attributes with a ``[[]]`` spelling are no longer diagnosed 
twice.
   This fixes Issue `Issue 54817 
`_.
-- Clang should no longer incorrectly diagnose a variable declaration inside of
-  a lambda expression that shares the name of a variable in a containing
-  if/while/for/switch init statement as a redeclaration.
-  This fixes `Issue 54913 
`_.
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/lib/Sema/IdentifierResolver.cpp 
b/clang/lib/Sema/IdentifierResolver.cpp
index 9081714c893f5..cef1ae890e6cb 100644
--- a/clang/lib/Sema/IdentifierResolver.cpp
+++ b/clang/lib/Sema/IdentifierResolver.cpp
@@ -123,7 +123,7 @@ bool IdentifierResolver::isDeclInScope(Decl *D, DeclContext 
*Ctx, Scope *S,
   assert(S->getParent() && "No TUScope?");
   // If the current decl is in a lambda, we shouldn't consider this is a
   // redefinition as lambda has its own scope.
-  if (S->getParent()->isControlScope() && !S->isFunctionScope()) {
+  if (S->getParent()->isControlScope()) {
 S = S->getParent();
 if (S->isDeclScope(D))
   return true;

diff  --git a/clang/test/SemaCXX/cxx1z-init-statement.cpp 
b/clang/test/SemaCXX/cxx1z-init-statement.cpp
index b963c9eabe79b..eea2589ab7c62 100644
--- a/clang/test/SemaCXX/cxx1z-init-statement.cpp
+++ b/clang/test/SemaCXX/cxx1z-init-statement.cpp
@@ -90,18 +90,3 @@ void test_constexpr_init_stmt() {
   static_assert(constexpr_switch_init(-2) == 0, "");
   static_assert(constexpr_switch_init(-5) == -1, "");
 }
-
-int test_lambda_init() {
-  if (int x = []() {int x = 42; return x; }(); x) {
-  };
-
-  switch (int y = []() {int y = 42; return y; }(); y) {
-  case 42:
-return 1;
-  }
-
-  for (int x = [] { int x = 0; return x; }();;)
-;
-
-  return 0;
-}



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


[clang] 7fde4e2 - Add some helpers to better check Scope's kind. NFC

2022-04-15 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-04-16T11:31:40+08:00
New Revision: 7fde4e221300dbdefe9cdd70ff59f22f1dc9aee9

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

LOG: Add some helpers to better check Scope's kind. NFC

Signed-off-by: Jun Zhang 

Added: 


Modified: 
clang/include/clang/Sema/Scope.h
clang/lib/Parse/ParseDecl.cpp
clang/lib/Parse/ParseDeclCXX.cpp
clang/lib/Parse/ParseStmt.cpp
clang/lib/Parse/Parser.cpp
clang/lib/Sema/IdentifierResolver.cpp
clang/lib/Sema/SemaCodeComplete.cpp
clang/lib/Sema/SemaCoroutine.cpp
clang/lib/Sema/SemaExprMember.cpp
clang/lib/Sema/SemaStmt.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Scope.h 
b/clang/include/clang/Sema/Scope.h
index 5a2d51b63d909..3255bdc8648df 100644
--- a/clang/include/clang/Sema/Scope.h
+++ b/clang/include/clang/Sema/Scope.h
@@ -370,11 +370,15 @@ class Scope {
   }
 
   /// isFunctionScope() - Return true if this scope is a function scope.
-  bool isFunctionScope() const { return (getFlags() & Scope::FnScope); }
+  bool isFunctionScope() const { return getFlags() & Scope::FnScope; }
 
   /// isClassScope - Return true if this scope is a class/struct/union scope.
-  bool isClassScope() const {
-return (getFlags() & Scope::ClassScope);
+  bool isClassScope() const { return getFlags() & Scope::ClassScope; }
+
+  /// Determines whether this scope is between inheritance colon and the real
+  /// class/struct definition.
+  bool isClassInheritanceScope() const {
+return getFlags() & Scope::ClassInheritanceScope;
   }
 
   /// isInCXXInlineMethodScope - Return true if this scope is a C++ inline
@@ -432,6 +436,9 @@ class Scope {
 return getFlags() & Scope::AtCatchScope;
   }
 
+  /// isCatchScope - Return true if this scope is a C++ catch statement.
+  bool isCatchScope() const { return getFlags() & Scope::CatchScope; }
+
   /// isSwitchScope - Return true if this scope is a switch scope.
   bool isSwitchScope() const {
 for (const Scope *S = this; S; S = S->getParent()) {
@@ -475,9 +482,20 @@ class Scope {
 return P && P->isOpenMPLoopDirectiveScope();
   }
 
+  /// Determine whether this scope is a while/do/for statement, which can have
+  /// continue statements embedded into it.
+  bool isContinueScope() const {
+return getFlags() & ScopeFlags::ContinueScope;
+  }
+
   /// Determine whether this scope is a C++ 'try' block.
   bool isTryScope() const { return getFlags() & Scope::TryScope; }
 
+  /// Determine whether this scope is a function-level C++ try or catch scope.
+  bool isFnTryCatchScope() const {
+return getFlags() & ScopeFlags::FnTryCatchScope;
+  }
+
   /// Determine whether this scope is a SEH '__try' block.
   bool isSEHTryScope() const { return getFlags() & Scope::SEHTryScope; }
 
@@ -489,6 +507,10 @@ class Scope {
 return getFlags() & Scope::CompoundStmtScope;
   }
 
+  /// Determine whether this scope is a controlling scope in a
+  /// if/switch/while/for statement.
+  bool isControlScope() const { return getFlags() & Scope::ControlScope; }
+
   /// Returns if rhs has a higher scope depth than this.
   ///
   /// The caller is responsible for calling this only if one of the two scopes

diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index ca55fa9311867..233f09213be8c 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -4624,8 +4624,8 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, 
DeclSpec ,
   TypeResult BaseType;
   SourceRange BaseRange;
 
-  bool CanBeBitfield = (getCurScope()->getFlags() & Scope::ClassScope) &&
-   ScopedEnumKWLoc.isInvalid() && Name;
+  bool CanBeBitfield =
+  getCurScope()->isClassScope() && ScopedEnumKWLoc.isInvalid() && Name;
 
   // Parse the fixed underlying type.
   if (Tok.is(tok::colon)) {
@@ -5021,7 +5021,7 @@ void Parser::ParseEnumBody(SourceLocation StartLoc, Decl 
*EnumDecl) {
 
   // The next token must be valid after an enum definition. If not, a ';'
   // was probably forgotten.
-  bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
+  bool CanBeBitfield = getCurScope()->isClassScope();
   if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
 // Push this token back into the preprocessor and change our current token
@@ -6753,8 +6753,7 @@ void Parser::ParseFunctionDeclarator(Declarator ,
   // this in C and not C++, where the decls will continue to live in the
   // surrounding context.
   SmallVector DeclsInPrototype;
-  if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
-  !getLangOpts().CPlusPlus) {
+  if (getCurScope()->isFunctionDeclarationScope() && !getLangOpts().CPlusPlus) 
{
 for (Decl *D : 

[clang] be0905a - [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

2022-04-15 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-04-15T21:54:39+08:00
New Revision: be0905a333d6f7c4d7f5c70c18211463e53473cd

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

LOG: [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

Clang should no longer incorrectly diagnose a variable declaration inside of a
lambda expression that shares the name of a variable in a containing
if/while/for/switch init statement as a redeclaration.

After this patch, clang is supposed to accept code below:

void foo() {
  for (int x = [] { int x = 0; return x; }(); ;) ;
}

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

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/IdentifierResolver.cpp
clang/test/SemaCXX/cxx1z-init-statement.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f5d3793225bfb..2497280dfdd6d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -119,6 +119,10 @@ Bug Fixes
   This fixes Issue `Issue 52802 
`_.
 - Unknown type attributes with a ``[[]]`` spelling are no longer diagnosed 
twice.
   This fixes Issue `Issue 54817 
`_.
+- Clang should no longer incorrectly diagnose a variable declaration inside of
+  a lambda expression that shares the name of a variable in a containing
+  if/while/for/switch init statement as a redeclaration.
+  This fixes `Issue 54913 
`_.
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/lib/Sema/IdentifierResolver.cpp 
b/clang/lib/Sema/IdentifierResolver.cpp
index 333f4d70986a0..9c5d78fb25d9c 100644
--- a/clang/lib/Sema/IdentifierResolver.cpp
+++ b/clang/lib/Sema/IdentifierResolver.cpp
@@ -121,7 +121,10 @@ bool IdentifierResolver::isDeclInScope(Decl *D, 
DeclContext *Ctx, Scope *S,
   // of the controlled statement.
   //
   assert(S->getParent() && "No TUScope?");
-  if (S->getParent()->getFlags() & Scope::ControlScope) {
+  // If the current decl is in a lambda, we shouldn't consider this is a
+  // redefinition as lambda has its own scope.
+  if (S->getParent()->getFlags() & Scope::ControlScope &&
+  !S->isFunctionScope()) {
 S = S->getParent();
 if (S->isDeclScope(D))
   return true;

diff  --git a/clang/test/SemaCXX/cxx1z-init-statement.cpp 
b/clang/test/SemaCXX/cxx1z-init-statement.cpp
index eea2589ab7c62..b963c9eabe79b 100644
--- a/clang/test/SemaCXX/cxx1z-init-statement.cpp
+++ b/clang/test/SemaCXX/cxx1z-init-statement.cpp
@@ -90,3 +90,18 @@ void test_constexpr_init_stmt() {
   static_assert(constexpr_switch_init(-2) == 0, "");
   static_assert(constexpr_switch_init(-5) == -1, "");
 }
+
+int test_lambda_init() {
+  if (int x = []() {int x = 42; return x; }(); x) {
+  };
+
+  switch (int y = []() {int y = 42; return y; }(); y) {
+  case 42:
+return 1;
+  }
+
+  for (int x = [] { int x = 0; return x; }();;)
+;
+
+  return 0;
+}



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


[clang] f9c2f82 - [Clang] Fix unknown type attributes diagnosed twice with [[]] spelling

2022-04-12 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-04-12T21:11:51+08:00
New Revision: f9c2f821d71b7bbb2544a489b7798bd173ea8907

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

LOG: [Clang] Fix unknown type attributes diagnosed twice with [[]] spelling

Don't warn on unknown type attributes in Parser::ProhibitCXX11Attributes
for most cases, but left the diagnostic to the later checks.
module declaration and module import declaration are special cases.

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

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

Added: 
clang/test/SemaCXX/warn-once-on-unknown-attr.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Parse/Parser.h
clang/lib/Parse/ParseDecl.cpp
clang/lib/Parse/Parser.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index fbc1edb8e9e2a..a1ff6f8787bb1 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -117,6 +117,8 @@ Bug Fixes
   `C++20 [dcl.fct.def.general]p2 
`_,
   Clang should not diagnose incomplete types in function definitions if the 
function body is "= delete;".
   This fixes Issue `Issue 52802 
`_.
+- Unknown type attributes with a ``[[]]`` spelling are no longer diagnosed 
twice.
+  This fixes Issue `Issue 54817 
`_.
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index 3241931345297..d6cb68aaadca7 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -2633,8 +2633,12 @@ class Parser : public CodeCompletionHandler {
   // Forbid C++11 and C2x attributes that appear on certain syntactic locations
   // which standard permits but we don't supported yet, for example, attributes
   // appertain to decl specifiers.
+  // For the most cases we don't want to warn on unknown type attributes, but
+  // left them to later diagnoses. However, for a few cases like module
+  // declarations and module import declarations, we should do it.
   void ProhibitCXX11Attributes(ParsedAttributes , unsigned DiagID,
-   bool DiagnoseEmptyAttrs = false);
+   bool DiagnoseEmptyAttrs = false,
+   bool WarnOnUnknownAttrs = false);
 
   /// Skip C++11 and C2x attributes and return the end location of the
   /// last one.

diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 627b11fb6ac0c..f912d9d99efd9 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -1658,7 +1658,8 @@ void Parser::DiagnoseProhibitedAttributes(
 }
 
 void Parser::ProhibitCXX11Attributes(ParsedAttributes , unsigned DiagID,
- bool DiagnoseEmptyAttrs) {
+ bool DiagnoseEmptyAttrs,
+ bool WarnOnUnknownAttrs) {
 
   if (DiagnoseEmptyAttrs && Attrs.empty() && Attrs.Range.isValid()) {
 // An attribute list has been parsed, but it was empty.
@@ -1685,10 +1686,11 @@ void Parser::ProhibitCXX11Attributes(ParsedAttributes 
, unsigned DiagID,
   for (const ParsedAttr  : Attrs) {
 if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
   continue;
-if (AL.getKind() == ParsedAttr::UnknownAttribute)
-  Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
-  << AL << AL.getRange();
-else {
+if (AL.getKind() == ParsedAttr::UnknownAttribute) {
+  if (WarnOnUnknownAttrs)
+Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
+<< AL << AL.getRange();
+} else {
   Diag(AL.getLoc(), DiagID) << AL;
   AL.setInvalid();
 }

diff  --git a/clang/lib/Parse/Parser.cpp b/clang/lib/Parse/Parser.cpp
index f754388cdc7c8..2550cdd9f5bbf 100644
--- a/clang/lib/Parse/Parser.cpp
+++ b/clang/lib/Parse/Parser.cpp
@@ -2386,7 +2386,9 @@ Parser::ParseModuleDecl(Sema::ModuleImportState 
) {
   // We don't support any module attributes yet; just parse them and diagnose.
   ParsedAttributes Attrs(AttrFactory);
   MaybeParseCXX11Attributes(Attrs);
-  ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr);
+  ProhibitCXX11Attributes(Attrs, diag::err_attribute_not_module_attr,
+  /*DiagnoseEmptyAttrs=*/false,
+  /*WarnOnUnknownAttrs=*/true);
 
   ExpectAndConsumeSemi(diag::err_module_expected_semi);
 
@@ -2453,7 +2455,9 @@ Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
   ParsedAttributes Attrs(AttrFactory);
   

[clang-tools-extra] f2796a5 - Link aganist clangSema to fix broken build.

2022-04-06 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-04-07T10:50:50+08:00
New Revision: f2796a5d444998ea73f02f433ed34b7c09e0f7d5

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

LOG: Link aganist clangSema to fix broken build.

Signed-off-by: Jun Zhang 

Added: 


Modified: 
clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt 
b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
index a68e7157a5af0..3d59608a04239 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
+++ b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
@@ -37,6 +37,7 @@ add_clang_library(clangDaemonTweaks OBJECT
   clangdSupport
   clangFormat
   clangLex
+  clangSema
   clangToolingCore
   clangToolingRefactoring
   clangToolingSyntax



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


[clang] 8a4d388 - [Clang][Sema] Prohibit statement expression in the default argument

2022-04-05 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-04-06T09:28:20+08:00
New Revision: 8a4d388c7fa47fa50076babecc38757009dbc987

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

LOG: [Clang][Sema] Prohibit statement expression in the default argument

As statement expression makes no sense in the default argument,
this patch tries to disable it in the all cases.

Please note that the statement expression is a GNU extension, which
means that Clang should be consistent with GCC. However, there's no
response from GCC devs since we have raised the issue for several weeks.
In this case, I think we can disallow statement expressions as a default
parameter in general for now, and relax the restriction if GCC folks
decide to retain the feature for functions but not lambdas in the
future.

Related discussion: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104765

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

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

Added: 
clang/test/Sema/stmt-expr-in-default-arg.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Parse/ParseDecl.cpp
clang/lib/Parse/ParseTemplate.cpp
clang/test/SemaTemplate/dependent-expr.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 86d0a3e7303f1..bf592329ac02a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -97,6 +97,8 @@ Bug Fixes
 - The builtin function __builtin_dump_struct would crash clang when the target 
   struct contains a bitfield. It now correctly handles bitfields.
   This fixes Issue `Issue 54462 
`_.
+- Statement expressions are now disabled in default arguments in general.
+  This fixes Issue `Issue 53488 
`_.
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index c5171359e7e4c..96cd00c8bb2a1 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -4380,6 +4380,9 @@ def err_uninitialized_member_in_ctor : Error<
 def err_default_arg_makes_ctor_special : Error<
   "addition of default argument on redeclaration makes this constructor a "
   "%select{default|copy|move}0 constructor">;
+def err_stmt_expr_in_default_arg : Error<
+  "default %select{argument|non-type template argument}0 may not use a GNU "
+  "statement expression">;
 
 def err_use_of_default_argument_to_function_declared_later : Error<
   "use of default argument to function %0 that is declared later in class %1">;

diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index f07758197205f..627b11fb6ac0c 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -7066,8 +7066,16 @@ void Parser::ParseParameterDeclarationClause(
   if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
 DefArgResult = ParseBraceInitializer();
-  } else
+  } else {
+if (Tok.is(tok::l_paren) && NextToken().is(tok::l_brace)) {
+  Diag(Tok, diag::err_stmt_expr_in_default_arg) << 0;
+  Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
+  // Skip the statement expression and continue parsing
+  SkipUntil(tok::comma, StopBeforeMatch);
+  continue;
+}
 DefArgResult = ParseAssignmentExpression();
+  }
   DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
   if (DefArgResult.isInvalid()) {
 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);

diff  --git a/clang/lib/Parse/ParseTemplate.cpp 
b/clang/lib/Parse/ParseTemplate.cpp
index 211d1a33542b2..5687882251a05 100644
--- a/clang/lib/Parse/ParseTemplate.cpp
+++ b/clang/lib/Parse/ParseTemplate.cpp
@@ -19,6 +19,7 @@
 #include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/ParsedTemplate.h"
 #include "clang/Sema/Scope.h"
+#include "clang/Sema/SemaDiagnostic.h"
 #include "llvm/Support/TimeProfiler.h"
 using namespace clang;
 
@@ -1007,18 +1008,23 @@ Parser::ParseNonTypeTemplateParameter(unsigned Depth, 
unsigned Position) {
   SourceLocation EqualLoc;
   ExprResult DefaultArg;
   if (TryConsumeToken(tok::equal, EqualLoc)) {
-// C++ [temp.param]p15:
-//   When parsing a default template-argument for a non-type
-//   template-parameter, the first non-nested > is taken as the
-//   end of the template-parameter-list rather than a greater-than
-//   operator.
-

[clang] 5b38292 - [NFC] Use range based loop.

2022-03-30 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-03-30T22:44:34+08:00
New Revision: 5b38292d5d776439b54e7cc02c7a20c58717f3d2

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

LOG: [NFC] Use range based loop.

Signed-off-by: Jun Zhang 

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

Added: 


Modified: 
clang/lib/AST/ASTDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTDiagnostic.cpp b/clang/lib/AST/ASTDiagnostic.cpp
index 0c27c0d14519d..28269ec219e4c 100644
--- a/clang/lib/AST/ASTDiagnostic.cpp
+++ b/clang/lib/AST/ASTDiagnostic.cpp
@@ -270,9 +270,9 @@ ConvertTypeToDiagnosticString(ASTContext , QualType 
Ty,
   std::string S = Ty.getAsString(Context.getPrintingPolicy());
   std::string CanS = CanTy.getAsString(Context.getPrintingPolicy());
 
-  for (unsigned I = 0, E = QualTypeVals.size(); I != E; ++I) {
+  for (const intptr_t  : QualTypeVals) {
 QualType CompareTy =
-QualType::getFromOpaquePtr(reinterpret_cast(QualTypeVals[I]));
+QualType::getFromOpaquePtr(reinterpret_cast(QualTypeVal));
 if (CompareTy.isNull())
   continue;
 if (CompareTy == Ty)
@@ -302,11 +302,11 @@ ConvertTypeToDiagnosticString(ASTContext , 
QualType Ty,
   // Check to see if we already desugared this type in this
   // diagnostic.  If so, don't do it again.
   bool Repeated = false;
-  for (unsigned i = 0, e = PrevArgs.size(); i != e; ++i) {
+  for (const auto  : PrevArgs) {
 // TODO: Handle ak_declcontext case.
-if (PrevArgs[i].first == DiagnosticsEngine::ak_qualtype) {
-  void *Ptr = (void*)PrevArgs[i].second;
-  QualType PrevTy(QualType::getFromOpaquePtr(Ptr));
+if (PrevArg.first == DiagnosticsEngine::ak_qualtype) {
+  QualType PrevTy(
+  QualType::getFromOpaquePtr(reinterpret_cast(PrevArg.second)));
   if (PrevTy == Ty) {
 Repeated = true;
 break;



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


[clang] 17a6806 - [Clang] Use = default(NFC)

2022-03-05 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-03-06T14:25:22+08:00
New Revision: 17a68065c378da74805e4e1b9a5b78cc9f83e580

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

LOG: [Clang] Use = default(NFC)

Added: 


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

Removed: 




diff  --git a/clang/include/clang/Basic/Builtins.h 
b/clang/include/clang/Basic/Builtins.h
index 1dabafce54f39..2926e0fa2c8d6 100644
--- a/clang/include/clang/Basic/Builtins.h
+++ b/clang/include/clang/Basic/Builtins.h
@@ -70,7 +70,7 @@ class Context {
   llvm::ArrayRef AuxTSRecords;
 
 public:
-  Context() {}
+  Context() = default;
 
   /// Perform target-specific initialization
   /// \param AuxTarget Target info to incorporate builtins from. May be 
nullptr.



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


[clang-tools-extra] ac616fb - [Clang-tidy] Check the existence of ElaboratedType's qualifiers

2022-03-01 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-03-01T23:52:44+08:00
New Revision: ac616fbb05b8c0e8f85144d54d5295d2d663c5b7

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

LOG: [Clang-tidy] Check the existence of ElaboratedType's qualifiers

The ElaboratedType can have no qualifiers, so we should check it before
use.

Fix #issue53874(https://github.com/llvm/llvm-project/issues/53874)

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

Added: 


Modified: 

clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp

clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
 
b/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
index f2c1b0f5ec49b..0f73b1320de5a 100644
--- 
a/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
@@ -19,14 +19,15 @@ namespace readability {
 
 static unsigned getNameSpecifierNestingLevel(const QualType ) {
   if (const ElaboratedType *ElType = QType->getAs()) {
-const NestedNameSpecifier *NestedSpecifiers = ElType->getQualifier();
-unsigned NameSpecifierNestingLevel = 1;
-do {
-  NameSpecifierNestingLevel++;
-  NestedSpecifiers = NestedSpecifiers->getPrefix();
-} while (NestedSpecifiers);
-
-return NameSpecifierNestingLevel;
+if (const NestedNameSpecifier *NestedSpecifiers = ElType->getQualifier()) {
+  unsigned NameSpecifierNestingLevel = 1;
+  do {
+NameSpecifierNestingLevel++;
+NestedSpecifiers = NestedSpecifiers->getPrefix();
+  } while (NestedSpecifiers);
+
+  return NameSpecifierNestingLevel;
+}
   }
   return 0;
 }
@@ -68,6 +69,10 @@ void StaticAccessedThroughInstanceCheck::check(
   PrintingPolicy PrintingPolicyWithSupressedTag(AstContext->getLangOpts());
   PrintingPolicyWithSupressedTag.SuppressTagKeyword = true;
   PrintingPolicyWithSupressedTag.SuppressUnwrittenScope = true;
+
+  PrintingPolicyWithSupressedTag.PrintCanonicalTypes =
+  !BaseExpr->getType()->isTypedefNameType();
+
   std::string BaseTypeName =
   BaseType.getAsString(PrintingPolicyWithSupressedTag);
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
index cd8d198c3d47d..debf3b9222164 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
@@ -198,6 +198,28 @@ void static_through_instance() {
   h<4>();
 }
 
+struct SP {
+  static int I;
+} P;
+
+void usep() {
+  P.I;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member
+  // CHECK-FIXES: {{^}}  SP::I;{{$}}
+}
+
+namespace NSP {
+struct SP {
+  static int I;
+} P;
+} // namespace NSP
+
+void usensp() {
+  NSP::P.I;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member
+  // CHECK-FIXES: {{^}}  NSP::SP::I;{{$}}
+}
+
 // Overloaded member access operator
 struct Q {
   static int K;
@@ -237,9 +259,9 @@ void use_anonymous() {
 
 namespace Outer {
   inline namespace Inline {
-struct S {
-  static int I;
-};
+  struct S {
+static int I;
+  };
   }
 }
 



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


[clang] effd6dd - [Clang][Sema] Add a missing regression test about Wliteral-range

2022-02-14 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-02-15T09:46:42+08:00
New Revision: effd6dd63a65f201b4f8f1be6a025b0608604449

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

LOG: [Clang][Sema] Add a missing regression test about Wliteral-range

This patch adds a missing test, covering the different kinds of floating-point
literals, like hexadecimal floats, and testing extreme cases & normal cases.

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

Added: 
clang/test/Sema/warn-literal-range.c

Modified: 


Removed: 




diff  --git a/clang/test/Sema/warn-literal-range.c 
b/clang/test/Sema/warn-literal-range.c
new file mode 100644
index 0..8014b058bd886
--- /dev/null
+++ b/clang/test/Sema/warn-literal-range.c
@@ -0,0 +1,37 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -std=c99 -verify %s
+
+float f0 = 0.42f; // no-warning
+
+float f1 = 1.4E-46f; // expected-warning {{magnitude of floating-point 
constant too small for type 'float'; minimum is 1.40129846E-45}}
+
+float f2 = 3.4E+39f; // expected-warning {{magnitude of floating-point 
constant too large for type 'float'; maximum is 3.40282347E+38}}
+
+float f3 = 0x4.2p42f; // no-warning
+
+float f4 = 0x0.42p-1000f; // expected-warning {{magnitude of floating-point 
constant too small for type 'float'; minimum is 1.40129846E-45}}
+
+float f5 = 0x0.42p+1000f; // expected-warning {{magnitude of floating-point 
constant too large for type 'float'; maximum is 3.40282347E+38}}
+
+double d0 = 0.42; // no-warning
+
+double d1 = 3.6E-4952; // expected-warning {{magnitude of floating-point 
constant too small for type 'double'; minimum is 4.9406564584124654E-324}}
+
+double d2 = 1.7E+309; // expected-warning {{magnitude of floating-point 
constant too large for type 'double'; maximum is 1.7976931348623157E+308}}
+
+double d3 = 0x0.42p42; // no-warning
+
+double d4 = 0x0.42p-4200; // expected-warning {{magnitude of floating-point 
constant too small for type 'double'; minimum is 4.9406564584124654E-324}}
+
+double d5 = 0x0.42p+4200; // expected-warning {{magnitude of floating-point 
constant too large for type 'double'; maximum is 1.7976931348623157E+308}}
+
+long double ld0 = 0.42L; // no-warning
+
+long double ld1 = 3.6E-4952L; // expected-warning {{magnitude of 
floating-point constant too small for type 'long double'; minimum is 
3.64519953188247460253E-4951}}
+
+long double ld2 = 1.2E+4932L; // expected-warning {{magnitude of 
floating-point constant too large for type 'long double'; maximum is 
1.18973149535723176502E+4932}}
+
+long double ld3 = 0x0.42p42L; // no-warning
+
+long double ld4 = 0x0.42p-42000L; // expected-warning {{magnitude of 
floating-point constant too small for type 'long double'; minimum is 
3.64519953188247460253E-4951}}
+
+long double ld5 = 0x0.42p+42000L; // expected-warning {{magnitude of 
floating-point constant too large for type 'long double'; maximum is 
1.18973149535723176502E+4932}}



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


[clang] 65adf7c - [NFC][Analyzer] Use range based for loop.

2022-02-07 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-02-07T15:45:58+08:00
New Revision: 65adf7c2117ab2b2ff72a8c761164fb2c1b686c0

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

LOG: [NFC][Analyzer] Use range based for loop.

Use range base loop loop to improve code readability.

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp 
b/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
index b152f9d80ef5b..323c002d0cef6 100644
--- a/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ b/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -383,14 +383,14 @@ void 
AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
 }
 
 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
-  for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
+  for (auto  : DG) {
 
 // Skip ObjCMethodDecl, wait for the objc container to avoid
 // analyzing twice.
-if (isa(*I))
+if (isa(I))
   continue;
 
-LocalTUDecls.push_back(*I);
+LocalTUDecls.push_back(I);
   }
 }
 
@@ -462,11 +462,9 @@ void AnalysisConsumer::HandleDeclsCallGraph(const unsigned 
LocalTUDeclsSize) {
   SetOfConstDecls Visited;
   SetOfConstDecls VisitedAsTopLevel;
   llvm::ReversePostOrderTraversal RPOT();
-  for (llvm::ReversePostOrderTraversal::rpo_iterator
- I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
+  for (auto  : RPOT) {
 NumFunctionTopLevel++;
 
-CallGraphNode *N = *I;
 Decl *D = N->getDecl();
 
 // Skip the abstract root node.



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


[clang] 8de0c1f - [Clang] Add __builtin_reduce_or and __builtin_reduce_and

2022-01-14 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-01-14T22:05:26+08:00
New Revision: 8de0c1feca28e3de49b4d1d1140703cb6f739969

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

LOG: [Clang] Add __builtin_reduce_or and __builtin_reduce_and

This patch implements two builtins specified in D111529.
The last __builtin_reduce_add will be seperated into another one.

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

Added: 


Modified: 
clang/include/clang/Basic/Builtins.def
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/Sema/SemaChecking.cpp
clang/test/CodeGen/builtins-reduction-math.c
clang/test/Sema/builtins-reduction-math.c

Removed: 




diff  --git a/clang/include/clang/Basic/Builtins.def 
b/clang/include/clang/Basic/Builtins.def
index c7c47cf99aba..d2cb14d2fd8c 100644
--- a/clang/include/clang/Basic/Builtins.def
+++ b/clang/include/clang/Basic/Builtins.def
@@ -656,6 +656,8 @@ BUILTIN(__builtin_elementwise_trunc, "v.", "nct")
 BUILTIN(__builtin_reduce_max, "v.", "nct")
 BUILTIN(__builtin_reduce_min, "v.", "nct")
 BUILTIN(__builtin_reduce_xor, "v.", "nct")
+BUILTIN(__builtin_reduce_or, "v.", "nct")
+BUILTIN(__builtin_reduce_and, "v.", "nct")
 
 BUILTIN(__builtin_matrix_transpose, "v.", "nFt")
 BUILTIN(__builtin_matrix_column_major_load, "v.", "nFt")

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 187a603ff1c5..f68b7d3260e1 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3221,6 +3221,12 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   case Builtin::BI__builtin_reduce_xor:
 return RValue::get(emitUnaryBuiltin(
 *this, E, llvm::Intrinsic::vector_reduce_xor, "rdx.xor"));
+  case Builtin::BI__builtin_reduce_or:
+return RValue::get(emitUnaryBuiltin(
+*this, E, llvm::Intrinsic::vector_reduce_or, "rdx.or"));
+  case Builtin::BI__builtin_reduce_and:
+return RValue::get(emitUnaryBuiltin(
+*this, E, llvm::Intrinsic::vector_reduce_and, "rdx.and"));
 
   case Builtin::BI__builtin_matrix_transpose: {
 auto *MatrixTy = E->getArg(0)->getType()->castAs();

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index d067ac31dc1e..a17ede85d3eb 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -2237,8 +2237,10 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, 
unsigned BuiltinID,
 break;
   }
 
-  // __builtin_reduce_xor supports vector of integers only.
-  case Builtin::BI__builtin_reduce_xor: {
+  // These builtins support vectors of integers only.
+  case Builtin::BI__builtin_reduce_xor:
+  case Builtin::BI__builtin_reduce_or:
+  case Builtin::BI__builtin_reduce_and: {
 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
   return ExprError();
 

diff  --git a/clang/test/CodeGen/builtins-reduction-math.c 
b/clang/test/CodeGen/builtins-reduction-math.c
index babd3345d787..43d47fc9dbfe 100644
--- a/clang/test/CodeGen/builtins-reduction-math.c
+++ b/clang/test/CodeGen/builtins-reduction-math.c
@@ -68,3 +68,25 @@ void test_builtin_reduce_xor(si8 vi1, u4 vu1) {
   // CHECK-NEXT: call i32 @llvm.vector.reduce.xor.v4i32(<4 x i32> [[VU1]])
   unsigned r3 = __builtin_reduce_xor(vu1);
 }
+
+void test_builtin_reduce_or(si8 vi1, u4 vu1) {
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.or.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_or(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.or.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_or(vu1);
+}
+
+void test_builtin_reduce_and(si8 vi1, u4 vu1) {
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.and.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_and(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.and.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_and(vu1);
+}

diff  --git a/clang/test/Sema/builtins-reduction-math.c 
b/clang/test/Sema/builtins-reduction-math.c
index 8ee64d50de38..a72922605603 100644
--- a/clang/test/Sema/builtins-reduction-math.c
+++ b/clang/test/Sema/builtins-reduction-math.c
@@ -52,3 +52,37 @@ void test_builtin_reduce_xor(int i, float4 v, int3 iv) {
   i = __builtin_reduce_xor(v);
   // expected-error@-1 {{1st argument must be a vector of integers (was 
'float4' (vector of 4 'float' values))}}
 }
+
+void test_builtin_reduce_or(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_or(iv);
+  // expected-error@-1 {{initializing 'struct Foo' 

[clang] 5be1319 - [NFC] Test commit.

2022-01-07 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-01-08T10:36:09+08:00
New Revision: 5be131922cb78b4d1ff9bbfe4f524261c12f9cf8

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

LOG: [NFC] Test commit.

This is just a test commit to check whether the permission I got is
correct or not.

Added: 


Modified: 
clang/lib/CodeGen/CGBuiltin.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index e98c9d5fd8444..716134b123dd6 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -159,6 +159,7 @@ static Value *EmitFromInt(CodeGenFunction , llvm::Value 
*V,
 static Value *MakeBinaryAtomicValue(
 CodeGenFunction , llvm::AtomicRMWInst::BinOp Kind, const CallExpr *E,
 AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
+
   QualType T = E->getType();
   assert(E->getArg(0)->getType()->isPointerType());
   assert(CGF.getContext().hasSameUnqualifiedType(T,



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