Tablegen foreach

I’m trying to find examples of the foreach pattern being used in tablegen files.

The problem I am trying to solve is to simplify the amount of tablegen code I have to produce because each operand of an instruction can be a register or a literal.

So for binary, we have 4 instructions, ternary, 8, and quaternary 16 combinations.

Instead of writing all the combinations out, I’d like to use nested foreach loops to generate, the problem I’m having is that I cannot seem to conditionally set a DAG node on the foreach variable.

For example:

foreach a in [“r”, “I”] in {

def ADD#a : Inst<!if(!eq(#a, “r”), i32Reg, i32imm)>;


So, is this possible? It seems to be no to me. What could be another way of doing this without having massive code duplication.



I think a multiclass may be a better fit for what you are trying to
do. In fact, this is the canonical example for multiclasses:

--Sean Silva

That is what I currently have, I'm trying to simplify them even further since my multiclass file is enormous because of the amount of combinations. I have things like this:

multiclass instmcRegImm<...> {
def rr: inst<...>;
def ri: inst<...>;
def ir: inst<...>;
def ii: inst<...>;
multiclass instmc<...> {
defm i8 : instmcRegImm<...>;
^-- repeat for 15 more register classes.
defm INST : instMC<..>;

Then I need to repeat this for SDNodes, PatFrags, Intrinsics, etc... This doesn't even take into account special case instructions. I know that Owen's work on overloaded nodes will help here, but even then, it is just a lot of duplicate code.


I believe multiclasses can be nested. Could that help you reduce the

--Sean Silva

I believe multiclasses can be nested. Could that help you reduce the

Yes they can. I believe X86 does so, for example.