Clarifying usage of `const`

Signal boosting the discussion in ⚙ D115596 [mlir] Make LLVMIR Dialect types const correct : we are very inconsistent in placing const on methods of IR types. The rationale on (not) using const is ambiguous on this point as it explicitly says it does not concern “immutable” types such as attributes, but the types themselves become (a) mutable and (b) values (the doc was written when these were pointers, or barely wrapped pointers). At the same time, interfaces currently require method implementations to be marked const.

What are the thoughts on this?

My tentative thinking is to encourage const methods when appropriate, but discourage passing-by-const -something (which is mostly pointless since we pass IR objects other than Operation by-value).

The intention of that doc was that methods should not be marked const - that is implicit in the fact that they are immutable types, and it is better to be consistent about it than not.

I’ve seen one place this came up as a problem: in generic code you can get things that passes you a const reference to a pair<Type, thing>, which makes its element types const, which means you can’t access the members. You have to extract the element out to a temporary, which seems silly.

API consistency is important to me. If we care about solving this, I think we should flop completely the other way and mandate const everywhere. I don’t think we should be in a split situation.

-Chris

The rationale is very convincing in terms of the IR object (Operation, Region, Block), but it isn’t clear to me about Type/Attributes though? It seems that most of the methods on these could be fundamentally const without any of the consequence we were trying to protect against with the mutable IR entities, wouldn’t they?

On a side note, types/attributes are somehow mutable now but we’re lacking documentation and guidelines on how to bound this for users: it seems easy right now for a user to just think: “oh I can just make all of my type/attr data mutable”.

You’re absolutely right. I just did another pass over the doc and I agree that it would be much more principled and consistent to make methods on attributes and types be const. The -> operator on Attribute and Type could return a const pointer for example.