HomePhabricator

[StringExtras] Add a helper class for comma-separated lists

Authored by kazu on Sun, Jan 10, 2:32 PM.

Description

[StringExtras] Add a helper class for comma-separated lists

This patch introduces a helper class SubsequentDelim to simplify loops
that generate a comma-separated lists.

For example, consider the following loop, taken from
llvm/lib/CodeGen/MachineBasicBlock.cpp:

for (auto I = pred_begin(), E = pred_end(); I != E; ++I) {
  if (I != pred_begin())
    OS << ", ";
  OS << printMBBReference(**I);
}

The new class allows us to rewrite the loop as:

SubsequentDelim SD;
for (auto I = pred_begin(), E = pred_end(); I != E; ++I)
  OS << SD << printMBBReference(**I);

where SD evaluates to the empty string for the first time and ", " for
subsequent iterations.

Unlike interleaveComma, defined in llvm/include/llvm/ADT/STLExtras.h,
SubsequentDelim can accommodate a wider variety of loops, including:

  • those that conditionally skip certain items,
  • those that need iterators to call getSuccProbability(I), and
  • those that iterate over integer ranges.

As an example, this patch cleans up MachineBasicBlock::print.

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