Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion clang/include/clang/CIR/MissingFeatures.h
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,6 @@ struct MissingFeatures {
static bool targetSpecificCXXABI() { return false; }
static bool moduleNameHash() { return false; }
static bool setDSOLocal() { return false; }
static bool foldCaseStmt() { return false; }
static bool constantFoldSwitchStatement() { return false; }

// Missing types
Expand Down
7 changes: 7 additions & 0 deletions clang/lib/CIR/CodeGen/CIRGenFunction.h
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,9 @@ class CIRGenFunction : public CIRGenTypeCache {
/// addressed later.
RValue getUndefRValue(clang::QualType ty);

const CaseStmt *foldCaseStmt(const clang::CaseStmt &s, mlir::Type condType,
mlir::ArrayAttr &value, cir::CaseOpKind &kind);

cir::FuncOp generateCode(clang::GlobalDecl gd, cir::FuncOp fn,
cir::FuncType funcType);

Expand Down Expand Up @@ -532,6 +535,10 @@ class CIRGenFunction : public CIRGenTypeCache {
mlir::LogicalResult emitDeclStmt(const clang::DeclStmt &s);
LValue emitDeclRefLValue(const clang::DeclRefExpr *e);

mlir::LogicalResult emitDefaultStmt(const clang::DefaultStmt &s,
mlir::Type condType,
bool buildingTopLevelCase);

/// Emit an `if` on a boolean condition to the specified blocks.
/// FIXME: Based on the condition, this might try to simplify the codegen of
/// the conditional based on the branch.
Expand Down
79 changes: 63 additions & 16 deletions clang/lib/CIR/CodeGen/CIRGenStmt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ mlir::LogicalResult CIRGenFunction::emitSimpleStmt(const Stmt *s,
case Stmt::NullStmtClass:
break;
case Stmt::CaseStmtClass:
case Stmt::DefaultStmtClass:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does 'top level' switch case mean here? I realize it is pre-existing, but trying to grok what is going on here

// If we reached here, we must not handling a switch case in the top level.
return emitSwitchCase(cast<SwitchCase>(*s),
/*buildingTopLevelCase=*/false);
Expand Down Expand Up @@ -428,6 +429,52 @@ mlir::LogicalResult CIRGenFunction::emitBreakStmt(const clang::BreakStmt &s) {
return mlir::success();
}

const CaseStmt *CIRGenFunction::foldCaseStmt(const clang::CaseStmt &s,
mlir::Type condType,
mlir::ArrayAttr &value,
cir::CaseOpKind &kind) {
const CaseStmt *caseStmt = &s;
const CaseStmt *lastCase = &s;
SmallVector<mlir::Attribute, 4> caseEltValueListAttr;

// Fold cascading cases whenever possible to simplify codegen a bit.
while (caseStmt) {
lastCase = caseStmt;

auto intVal = caseStmt->getLHS()->EvaluateKnownConstInt(getContext());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
auto intVal = caseStmt->getLHS()->EvaluateKnownConstInt(getContext());
APSInt intVal = caseStmt->getLHS()->EvaluateKnownConstInt(getContext());

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't use auto here, or 447.


if (auto *rhs = caseStmt->getRHS()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (auto *rhs = caseStmt->getRHS()) {
// If the case statement has an RHS value, it is representing a GNU
// case range statement, where LHS is the beginning of the range
// and RHS is the end of the range.
if (const Expr *rhs = caseStmt->getRHS()) {

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RHS is only valid for a GNU-range version of a case, do we have a test for that?

auto endVal = rhs->EvaluateKnownConstInt(getContext());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
auto endVal = rhs->EvaluateKnownConstInt(getContext());
APSInt endVal = rhs->EvaluateKnownConstInt(getContext());

SmallVector<mlir::Attribute, 4> rangeCaseAttr = {
cir::IntAttr::get(condType, intVal),
cir::IntAttr::get(condType, endVal)};
value = builder.getArrayAttr(rangeCaseAttr);
kind = cir::CaseOpKind::Range;

// We may not be able to fold rangaes. Due to we can't present range case
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rangaes -> ranges

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// We may not be able to fold rangaes. Due to we can't present range case
// We don't currently fold case range statements with other case statements.
// TODO(cir): Add this capability.

// with other trivial cases now.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds like it deserves an assert on missing features?

return caseStmt;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It took me a while to figure this out, but the check on line 465 guarantees that we will never get here unless this was the first case we are trying to fold. Can you add an assertion that verifies that? If the code is ever changed to make this untrue, we could easily lose cases.

}

caseEltValueListAttr.push_back(cir::IntAttr::get(condType, intVal));

caseStmt = dyn_cast_or_null<CaseStmt>(caseStmt->getSubStmt());

// Break early if we found ranges. We can't fold ranges due to the same
// reason above.
if (caseStmt && caseStmt->getRHS())
break;
}

if (!caseEltValueListAttr.empty()) {
value = builder.getArrayAttr(caseEltValueListAttr);
kind = caseEltValueListAttr.size() > 1 ? cir::CaseOpKind::Anyof
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So IIRC, 'anyof' is only valid if the case statements themselves are empty, right? Else they could contain a label for a GOTO, or be a duffs-device/etc. So i think we're being overly aggressive about joining these up here.

That said, i find myself wondering if the FE should be doing this sort of joining at all, rather than as a very early 'normalization' opt-pass.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that this should be moved to an optimization pass. Perhaps CIRSimplify?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cir-simplify isn't upstreamed yet should I go ahead and create it ?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer we do it in a followup, but it might be nice to see that sort of thing happen.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just to confirm in this case, should I leave the current code and add a TODO for the follow-up work?
Because if we move this logic to a pass , that means the tests will need to change as well, since the anyof won't be emitted until after the simplify is upstreamed.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer to just change the tests. The simplify pass shouldn't be run for the emit-cir tests unless it's explicitly added. There are a number of cases where we're doing optimization like this in the front end, and I really don't think we should be.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI, @mmha has been working on cir-simplify and will be posting a PR soon, so you should wait for that to land and then add the case folding after it is in place.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we're no longer folding cascading case statements, then this function could be simplified we wouldn’t need the while loop anymore since we're just extracting the kind and value from a single case. In that scenario, the assertion proposed by @andykaylor would no longer be necessary, because range cases would only ever be processed once at the top level.

const CaseStmt *CIRGenFunction::foldCaseStmt(const clang::CaseStmt &s,
                                             mlir::Type condType,
                                             mlir::ArrayAttr &value,
                                             cir::CaseOpKind &kind) {
  const CaseStmt *caseStmt = &s;
  SmallVector<mlir::Attribute, 1> caseEltValueListAttr;

  llvm::APSInt intVal = caseStmt->getLHS()->EvaluateKnownConstInt(getContext());

  // If the case statement has an RHS value, it is representing a GNU
  // case range statement, where LHS is the beginning of the range
  // and RHS is the end of the range.
  if (const Expr *rhs = caseStmt->getRHS()) {
    assert(caseStmt == &s && "Range case must be the first case processed");
    llvm::APSInt endVal = rhs->EvaluateKnownConstInt(getContext());
    SmallVector<mlir::Attribute, 4> rangeCaseAttr = {
        cir::IntAttr::get(condType, intVal),
        cir::IntAttr::get(condType, endVal)};
    value = builder.getArrayAttr(rangeCaseAttr);
    kind = cir::CaseOpKind::Range;

    // We don't currently fold case range statements with other case statements.
    // TODO(cir): Add this capability.
    assert(!cir::MissingFeatures::foldRangeCase());
    return caseStmt;
  }

  caseEltValueListAttr.push_back(cir::IntAttr::get(condType, intVal));

  if (!caseEltValueListAttr.empty()) {
    value = builder.getArrayAttr(caseEltValueListAttr);
    kind = cir::CaseOpKind::Equal;
  }

  return caseStmt;
}

We don’t need the while loop anymore because we must break as soon as we encounter a cascading case or default statement.

// Break early if we found a range. We can't fold ranges.
// Also break if we found a cascading case/default.
if (caseStmt) {
  const Stmt *sub = caseStmt->getSubStmt();
  if (caseStmt->getRHS() || isa<CaseStmt>(sub) || isa<DefaultStmt>(sub))
    break;
}

Also, given that we're no longer folding multiple cases, I think we should consider renaming the function to better reflect its new behavior. Something like getCaseInfo ?
Is my approach correct ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would say you don't even need to call a function at all. You can go back to what you had before in emitCaseStmt but with special handling added for the GNU range case.

: cir::CaseOpKind::Equal;
}

return lastCase;
}

template <typename T>
mlir::LogicalResult
CIRGenFunction::emitCaseDefaultCascade(const T *stmt, mlir::Type condType,
Expand Down Expand Up @@ -500,8 +547,8 @@ CIRGenFunction::emitCaseDefaultCascade(const T *stmt, mlir::Type condType,
if (subStmtKind == SubStmtKind::Case) {
result = emitCaseStmt(*cast<CaseStmt>(sub), condType, buildingTopLevelCase);
} else if (subStmtKind == SubStmtKind::Default) {
getCIRGenModule().errorNYI(sub->getSourceRange(), "Default case");
return mlir::failure();
result = emitDefaultStmt(*cast<DefaultStmt>(sub), condType,
buildingTopLevelCase);
} else if (buildingTopLevelCase) {
// If we're building a top level case, try to restore the insert point to
// the case we're building, then we can attach more random stmts to the
Expand All @@ -515,19 +562,20 @@ CIRGenFunction::emitCaseDefaultCascade(const T *stmt, mlir::Type condType,
mlir::LogicalResult CIRGenFunction::emitCaseStmt(const CaseStmt &s,
mlir::Type condType,
bool buildingTopLevelCase) {
llvm::APSInt intVal = s.getLHS()->EvaluateKnownConstInt(getContext());
SmallVector<mlir::Attribute, 1> caseEltValueListAttr;
caseEltValueListAttr.push_back(cir::IntAttr::get(condType, intVal));
mlir::ArrayAttr value = builder.getArrayAttr(caseEltValueListAttr);
if (s.getRHS()) {
getCIRGenModule().errorNYI(s.getSourceRange(), "SwitchOp range kind");
return mlir::failure();
}
assert(!cir::MissingFeatures::foldCaseStmt());
return emitCaseDefaultCascade(&s, condType, value, cir::CaseOpKind::Equal,
cir::CaseOpKind kind;
mlir::ArrayAttr value;
const CaseStmt *caseStmt = foldCaseStmt(s, condType, value, kind);
return emitCaseDefaultCascade(caseStmt, condType, value, kind,
buildingTopLevelCase);
}

mlir::LogicalResult CIRGenFunction::emitDefaultStmt(const clang::DefaultStmt &s,
mlir::Type condType,
bool buildingTopLevelCase) {
return emitCaseDefaultCascade(&s, condType, builder.getArrayAttr({}),
cir::CaseOpKind::Default, buildingTopLevelCase);
}

mlir::LogicalResult CIRGenFunction::emitSwitchCase(const SwitchCase &s,
bool buildingTopLevelCase) {
assert(!condTypeStack.empty() &&
Expand All @@ -537,10 +585,9 @@ mlir::LogicalResult CIRGenFunction::emitSwitchCase(const SwitchCase &s,
return emitCaseStmt(cast<CaseStmt>(s), condTypeStack.back(),
buildingTopLevelCase);

if (s.getStmtClass() == Stmt::DefaultStmtClass) {
getCIRGenModule().errorNYI(s.getSourceRange(), "Default case");
return mlir::failure();
}
if (s.getStmtClass() == Stmt::DefaultStmtClass)
return emitDefaultStmt(cast<DefaultStmt>(s), condTypeStack.back(),
buildingTopLevelCase);

llvm_unreachable("expect case or default stmt");
}
Expand Down
Loading