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

Aaron Ballman via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Tue May 2 08:48:21 PDT 2023


aaron.ballman added inline comments.


================
Comment at: clang/include/clang/Interpreter/Value.h:46
+
+#define REPL_BUILTIN_TYPES                                                     \
+  X(bool, Bool)                                                                \
----------------
v.g.vassilev wrote:
> aaron.ballman wrote:
> > v.g.vassilev wrote:
> > > aaron.ballman wrote:
> > > > Is this expected to be a complete list of builtin types? e.g., should this have `char8_t` and `void` and `wchar_t`, etc? Should this be including `clang/include/clang/AST/BuiltinTypes.def` instead of manually maintaining the list?
> > > This is used for various things including storing the bits into a big-endian agnostic way. For `void` we have a special case in the Value and we cannot define a union of a `void` type. We can include the others that you suggest. All the relevant ones are described in `clang::BuiltinType::getName`.
> > > 
> > > We cannot use `BuiltinTypes.def` because we want to have a mapping between the type as written in the language (eg, `bool`, `unsigned`, etc) and its underlying type name. That mapping is not available in `BuiltinTypes.def`. Ideally we should extend `BuiltinTypes.def` somehow but I'd prefer outside of this patch. One of the challenges is that some of the types depend on the language options (eg. `_Bool` vs `bool`) and I am not sure this can be resolved by tablegen.
> > > 
> > > On a broader perspective, the `Value` class is responsible for two things: (a) get a value from the interpreter to compiled code (see test case); (b) set a value from compiled code to the interpreter. The second case is not yet covered (I can open soon another patch). The major use-case is calling at runtime functions and taking input parameters from compiled code.
> > > 
> > > FWIW, we should probably move all of these entities in a separate namespace. I'd suggest `caas` (compiler-as-a-service) and possibly rename the `Value` to `InterpreterValue` since `Value` is very generic and there are already a couple of classes with that name in llvm and clang. 
> > > We can include the others that you suggest. All the relevant ones are described in clang::BuiltinType::getName.
> > 
> > Okay, so the plan is to handle all the builtin types (`_BitInt`, `_Complex`, various floating point formats, etc)? Will that be part of this patch or in follow-up work? (My intuition is that we should consider it up front because some of the builtin types are interesting -- like `_BitInt` because it's parameterized, which makes it novel compared to the other types.)
> > 
> > > We cannot use BuiltinTypes.def because we want to have a mapping between the type as written in the language (eg, bool, unsigned, etc) and its underlying type name. That mapping is not available in BuiltinTypes.def. Ideally we should extend BuiltinTypes.def somehow but I'd prefer outside of this patch. One of the challenges is that some of the types depend on the language options (eg. _Bool vs bool) and I am not sure this can be resolved by tablegen.
> > 
> > Thanks for the explanation! BuiltinTypes.def works well enough for times when we want to use macros and include the file to generate switch cases and the likes, but you're right that it's not well-suited for this. One thing to consider is whether we should change `BuiltinTypes.def` to be `BuiltinTypes.td` instead and use tablegen to generate the macro/include dance form as well as other output (such as for your needs, that can then consider language options or more complex predicates).
> > 
> > > FWIW, we should probably move all of these entities in a separate namespace. I'd suggest caas (compiler-as-a-service) and possibly rename the Value to InterpreterValue since Value is very generic and there are already a couple of classes with that name in llvm and clang.
> > 
> > I'm not in love with the name `caas` because that's not really a common acronym or abbreviation (and it looks like a typo due to `aa`). However, we already have an `interp` namespace in Clang for one of the other interpreters (constant expression evaluation), so that's not available for use. How about `repl` though?
> > 
> > As for considering changing the name from `Value` because of how many other `Value` types we have already... that's both a reason to rename and reason not to rename. I think I'm fine leaving it as `Value` so long as it's in a novel namespace.
> > > We can include the others that you suggest. All the relevant ones are described in clang::BuiltinType::getName.
> > 
> > Okay, so the plan is to handle all the builtin types (`_BitInt`, `_Complex`, various floating point formats, etc)? Will that be part of this patch or in follow-up work? (My intuition is that we should consider it up front because some of the builtin types are interesting -- like `_BitInt` because it's parameterized, which makes it novel compared to the other types.)
> 
> That's a good point. I think the current patch offers a new capability and it is probably fine to not address all at once. My concern is that @junaire has a month to work on these things and this patch is the first out of two patches. The risk here is to drop the ball on that altogether if we add more work as a requirement for that patch to go in.
> 
> 
> > 
> > > We cannot use BuiltinTypes.def because we want to have a mapping between the type as written in the language (eg, bool, unsigned, etc) and its underlying type name. That mapping is not available in BuiltinTypes.def. Ideally we should extend BuiltinTypes.def somehow but I'd prefer outside of this patch. One of the challenges is that some of the types depend on the language options (eg. _Bool vs bool) and I am not sure this can be resolved by tablegen.
> > 
> > Thanks for the explanation! BuiltinTypes.def works well enough for times when we want to use macros and include the file to generate switch cases and the likes, but you're right that it's not well-suited for this. One thing to consider is whether we should change `BuiltinTypes.def` to be `BuiltinTypes.td` instead and use tablegen to generate the macro/include dance form as well as other output (such as for your needs, that can then consider language options or more complex predicates).
> 
> I am totally with you here. I am not sure how to do this since as of now some of the types and their form as written are decided with a flag (IIRC the various `char` flavors).
> 
> > 
> > > FWIW, we should probably move all of these entities in a separate namespace. I'd suggest caas (compiler-as-a-service) and possibly rename the Value to InterpreterValue since Value is very generic and there are already a couple of classes with that name in llvm and clang.
> > 
> > I'm not in love with the name `caas` because that's not really a common acronym or abbreviation (and it looks like a typo due to `aa`). However, we already have an `interp` namespace in Clang for one of the other interpreters (constant expression evaluation), so that's not available for use. How about `repl` though?
> 
> The only problem I have with `repl` is misleading. `repl` usually means to people something that you run at your prompt and can type some expressions in and see some results. However, here we are building a foundational primitive to allow embedding an interpreter as part of your static program and be able to cross the compiler/interpreter boundary. The compiler-as-a-service (caas) is probably the closest I could find in CS research terminology to describe that. Would adding some solid bits of documentation to the entire approach make you more comfortable with that naming? 
> 
> FWIW, the namespace comment should not be a requirement for this particular patch. I think it is totally fine to keep it as it is and do the change outside of this patch to help the review. Moreover, we will probably need to move some of the existing components already.
> 
> > 
> > As for considering changing the name from `Value` because of how many other `Value` types we have already... that's both a reason to rename and reason not to rename. I think I'm fine leaving it as `Value` so long as it's in a novel namespace.
> 
> Ok, if that's not confusing, then let's keep it the way it was. That way it should be easier to adopt that downstream for sure!
> 
> 
>>>We can include the others that you suggest. All the relevant ones are described in clang::BuiltinType::getName.
>> Okay, so the plan is to handle all the builtin types (_BitInt, _Complex, various floating point formats, etc)? Will that be part of this patch or in follow-up work? (My intuition is that we should consider it up front because some of the builtin types are interesting -- like _BitInt because it's parameterized, which makes it novel compared to the other types.)
> That's a good point. I think the current patch offers a new capability and it is probably fine to not address all at once. My concern is that @junaire has a month to work on these things and this patch is the first out of two patches. The risk here is to drop the ball on that altogether if we add more work as a requirement for that patch to go in.

Yeah, the current patch is incremental progress, so I think it's defensible to leave this to follow-up work. But I worry that follow-up work is going to be hampered by the design choices made here, and I mostly want to avoid a situation where this works inconsistently and that's "good enough" for an extended period of time. It feels a bit like working with any builtin type is part of the MVP. However, I don't insist because this is still useful forward progress for a lot of use cases.

> The only problem I have with repl is misleading. repl usually means to people something that you run at your prompt and can type some expressions in and see some results. However, here we are building a foundational primitive to allow embedding an interpreter as part of your static program and be able to cross the compiler/interpreter boundary. The compiler-as-a-service (caas) is probably the closest I could find in CS research terminology to describe that. Would adding some solid bits of documentation to the entire approach make you more comfortable with that naming?

On the one hand, if we have to document what the name means, the name isn't very meaningful. On the other hand, we use `ento` for the static analyzer (because of "entomologist", one who studies bugs...), so I don't think users routinely get hung up by not understanding the namespace identifier. If you think `caas` is the best name for this, then let's go with that unless someone has a better suggestion.

> FWIW, the namespace comment should not be a requirement for this particular patch. I think it is totally fine to keep it as it is and do the change outside of this patch to help the review. Moreover, we will probably need to move some of the existing components already.

Agreed.


================
Comment at: clang/include/clang/Interpreter/Value.h:83
+  Value() = default;
+  Value(void /*Interpreter*/ *In, void /*QualType*/ *Ty);
+  Value(const Value &RHS);
----------------
junaire wrote:
> aaron.ballman wrote:
> > v.g.vassilev wrote:
> > > junaire wrote:
> > > > aaron.ballman wrote:
> > > > > Why do these take `void *` instead of the expected type?
> > > > Yeah for the first parameter, we could just use `Interpreter*` but the second one is an opaque type so I think we should keep it?
> > > See my previous comments on performance. We cannot include anything bulky in the header file.
> > I think I understand why the design is the way it is, but it still makes me uneasy. The constructor takes a pointer to some bucket of bytes... no size information, no type information, etc. Just "here's a random pointer". And then later, we hope the user calls `setKind()` in a way that makes sense.
> > 
> > We need it to be fast, but we also need it to be correct -- the type system is the best tool for helping with that.
> Not really... The user doesn't need to call `setKind()` explicitly to construct a `Value`, the constructor will handle it automatically. See `ConvertQualTypeToKind` in `Value.cpp`. So if the pointer is just some garbage data, the constructor should fail before yielding out a valid instance.
Yeah, that's a fair point, except nothing actually validates that the opaque pointer you are handed is actually valid for anything because it eventually just does a reinterpret_cast, so I don't think the constructor will fail.


================
Comment at: clang/include/clang/Interpreter/Value.h:121
+    static T cast(const Value &V) {
+      if (V.isPointerOrObjectType())
+        return (T)(uintptr_t)V.getAs<void *>();
----------------
junaire wrote:
> aaron.ballman wrote:
> > v.g.vassilev wrote:
> > > aaron.ballman wrote:
> > > > Do we have to worry about member function pointers where a single pointer value may not be sufficient?
> > > I am not sure if I understand your comment correctly. We only store objects and not function/member pointers (perhaps in some pathological way one could do that but I'd say it is not supported). Here we want to know if we stored it as a non-builtin type we need to make the pointer-like casts. My take is that for now we shouldn't worry about member function pointers.
> > Given:
> > ```
> > struct Foo {
> > struct Base {
> >   virtual int bar();
> > };
> > 
> > struct Foo : Base {
> >   int bar() { return 12; }
> > };
> > 
> > int (Foo::*bar_ptr)() = &Foo::bar;
> > ```
> > The object `bar_ptr` requires two pointers of space to represent: https://godbolt.org/z/o81sbjKM6, so I'm wondering whether `Value` can represent `bar_ptr`
> I added a test case for this.
Thank you for the test case!


================
Comment at: clang/include/clang/Interpreter/Value.h:143
+  /// Values referencing an object are treated as pointers to the object.
+  template <typename T> T castAs() const { return CastFwd<T>::cast(*this); }
+
----------------
junaire wrote:
> aaron.ballman wrote:
> > v.g.vassilev wrote:
> > > junaire wrote:
> > > > aaron.ballman wrote:
> > > > > This doesn't match the usual pattern used in Clang where the `get` variant returns `nullptr` and the `cast` variant asserts if the cast would be invalid. Should we go with a similar approach?
> > > > These APIs are adopted in Cling and Cling will remove the old implementation and use the upstream version of the value printing feature at some point in the future. So @v.g.vassilev hope we can keep these APIs close to Cling's variants as much as we can. I don't have a strong opinion here, what's your take here? @v.g.vassilev 
> > > I probably see the confusion. The `getAs<T>` operation is only relevant for pointer types. For example we stored object of type `UserClass` as a pointer. For instance, I don't see how `getAs<float>` can return a `nullptr`. We can probably inline the implementation of `getAs` for non-pointer types into `castAs` and leave `getAs` unimplemented relying only on the explicit specialization bellow for pointers.
> > >  
> > > The `castAs` operation means take a valid bit representation and transforms it into the requested one. I don't think it can or should be ever invalid. Here we are reshuffling bits.
> > > 
> > >  These changes are very subtle and if we decide to make changes we should open a pull request against the ROOT project to make sure we are not breaking some important case. The reference implementation is here: https://github.com/root-project/root/blob/master/interpreter/cling/include/cling/Interpreter/Value.h
> > I think `castAs` can be invalid -- if you have the bits for a float and you try to cast it as a pointer, that's not going to lead to good things, right?
> > 
> > My point is largely that the names `getAs` and `castAs` have meaning within Clang already and this seems to assign slightly different meaning to them, which might trip folks up. It might be worth considering renaming them to something like `bitCast` and `pointerCast` (or something else, I'm not tied to these names)?
> We want to rename:
> getAs --> as
> castAs --> convertTo
> 
> Does these look good to you?
Yeah, I think those are good replacements, thank you!


================
Comment at: clang/include/clang/Interpreter/Value.h:160-162
+  // Interpreter, QualType are stored as void* to reduce dependencies.
+  void *Interp = nullptr;
+  void *OpaqueType = nullptr;
----------------
v.g.vassilev wrote:
> aaron.ballman wrote:
> > v.g.vassilev wrote:
> > > aaron.ballman wrote:
> > > > Why don't forward declares suffice if we're storing the information by pointer?
> > > This is a performance-critical class. We literally measure the instruction count for it. We practically cannot include anything in this header file because the class needs to included as part of the interpreter runtime. For example:
> > > 
> > > ```
> > > #include <clang/Interpreter/Value.h>
> > > Value ResultV;
> > > gInterpreter->evaluate("float i = 12.3; i++", &V);
> > > printf("Value is %d\n", ResultV.castAs<int>());
> > > ```
> > > 
> > > This is how you can do things in Cling. This not yet there but that's our next step.
> > > 
> > > For performance reasons we have the `ValueKind` optimization which allows us to perform most of the operations we need very fast. There are some operations such as printing the concrete type which need the actual `QualType` and so on but they are outside of the performance critical paths and it is okay to resort back to the real types providing the level of accuracy we need.
> > > 
> > That sounds like it's going to lead to maintenance problems in the long term, right? I can't think of another header file we say "don't touch this because it may impact runtime performance", and so I can easily imagine someone breaking your expectation that this file can't include anything else.
> > 
> > Is there a long-term plan for addressing this?
> We have a few components like the Lexer that are extremely prone to performance regressions.
> 
> In terms for a longer-term plan in addressing this there are some steps could help IMO. First, this component is relatively standalone and very few changes will be required over time, for these I am hoping to be listed as a reviewer. Second, we can add a comment in the include area, making a note that including anything here will degrade the performance of almost all interpreted code. Third, we will find out about this in our downstream use-cases as the things get significantly slower.
> 
> Neither is silver bullet but that's probably the best we could do at that time. Btw, we might be able to add a test that's part of LLVM's performance analysis infrastructure.
> Neither is silver bullet but that's probably the best we could do at that time. Btw, we might be able to add a test that's part of LLVM's performance analysis infrastructure.

Yeah, we should probably consider doing that. But to make sure I understand the performance concerns... when we change functionality in the lexer, we (potentially) slow down the lexing phase of compilation. That's straightforward and unsurprising. But in this case, it sounds like the act of including another header file in this header file will cause a runtime performance concern, even if no other changes are made. If I'm correct, I can't think of anything else in the compiler that works like that.


================
Comment at: clang/lib/Interpreter/Interpreter.cpp:512
+        size_t ArrSize = Ctx.getConstantArrayElementCount(ConstantArrTy);
+        Expr *ArrSizeExpr = IntegerLiteralExpr(Ctx, ArrSize);
+        Expr *Args[] = {E, AllocCall.get(), ArrSizeExpr};
----------------
The `ArrSize` argument is being passed for `Ptr` in the call... is that correct? (It makes sense to me, but I don't get why the parameter is named `Ptr` to begin with.)


================
Comment at: clang/lib/Interpreter/Interpreter.cpp:211
+    void __clang_Interpreter_SetValueNoAlloc(void*,void*,void*,unsigned long long);
+    template <class T, class = T (*)() /*disable for arrays*/>
+    void __clang_Interpreter_SetValueCopyArr(T* Src, void* Placement, unsigned long Size) {
----------------
junaire wrote:
> v.g.vassilev wrote:
> > Can you add an `#ifdef __cplusplus` and add a value printing tests that run in clang-repl in C mode?
> After a private chat, we decide to disable the feature in C mode because it sounds like a bad idea to give C incomplete value printing support.
Is that disable happening in this patch, or is it in a different patch?


================
Comment at: clang/lib/Interpreter/InterpreterUtils.cpp:19
+  const llvm::APInt Addr(8 * sizeof(void *), Ptr);
+  return IntegerLiteral::Create(C, Addr, C.getUIntPtrType(), SourceLocation());
+}
----------------
This question applies more generally than just this function, but should we be requiring these interfaces to supply a `SourceLocation` rather than hard-coding no location information? That can make it easier to see what's going on when dumping the AST for debugging purposes, etc even if it's not necessary for diagnostics or other reasons. (I don't insist, just a speculative question about the interface.)


================
Comment at: clang/lib/Interpreter/InterpreterUtils.cpp:55-58
+    if (const clang::TagDecl *TD = dyn_cast<clang::TagDecl>(Within))
+      if (!TD->getDefinition())
+        // No definition, no lookup result.
+        return nullptr;
----------------



================
Comment at: clang/lib/Interpreter/InterpreterUtils.h:38
+namespace clang {
+IntegerLiteral *IntegerLiteralExpr(ASTContext &C, uintptr_t Ptr);
+
----------------
What is `Ptr` pointing to?

Should this be renamed to `UIntPtrTLiteralExpr` with a comment that says it creates an integer literal whose type is `uinptr_t`?


================
Comment at: clang/lib/Interpreter/Value.cpp:99
+
+  if (const auto *ET = dyn_cast<EnumType>(QT.getTypePtr()))
+    QT = ET->getDecl()->getIntegerType();
----------------



================
Comment at: clang/lib/Interpreter/Value.cpp:102
+
+  if (!QT->isBuiltinType() || QT->castAs<BuiltinType>()->isNullPtrType())
+    return Value::K_PtrOrObj;
----------------
Then reuse `BT` below instead of converting it again. (It's usually a code smell to have isa<> followed by cast<> operations.)


================
Comment at: clang/lib/Interpreter/Value.cpp:91
+  static constexpr unsigned char Canary[8] = {0x4c, 0x37, 0xad, 0x8f,
+                                              0x2d, 0x23, 0x95, 0x91};
+};
----------------
junaire wrote:
> sgraenitz wrote:
> > Can we add a comment with an explanation of the magic numbers please?
> I'm uncertain if these numbers actually have specific meanings, I just copied them from Cling directly.
That's all the more reason to document the numbers -- should they stay in sync with Cling?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141215



More information about the cfe-commits mailing list