33#include "mlir/IR/Builders.h"
34#include "mlir/IR/IRMapping.h"
35#include "mlir/IR/PatternMatch.h"
43#include "llvm/ADT/DenseMap.h"
44#include "llvm/ADT/SetVector.h"
45#include "llvm/ADT/SmallVector.h"
46#include "llvm/TargetParser/Triple.h"
52#define GEN_PASS_DEF_CIREHABILOWERING
53#include "clang/CIR/Dialect/Passes.h.inc"
64static cir::FuncOp getOrCreateRuntimeFuncDecl(mlir::ModuleOp mod,
67 cir::FuncType funcTy) {
68 if (
auto existing = mod.lookupSymbol<cir::FuncOp>(
name))
71 mlir::OpBuilder builder(mod.getContext());
72 builder.setInsertionPointToEnd(mod.getBody());
73 auto funcOp = cir::FuncOp::create(builder, loc,
name, funcTy);
74 funcOp.setLinkage(cir::GlobalLinkageKind::ExternalLinkage);
87 explicit EHABILowering(mlir::ModuleOp mod)
88 : mod(mod), ctx(mod.getContext()), builder(ctx) {}
89 virtual ~EHABILowering() =
default;
92 virtual mlir::LogicalResult
run() = 0;
96 mlir::MLIRContext *ctx;
97 mlir::OpBuilder builder;
111class ItaniumEHLowering :
public EHABILowering {
113 using EHABILowering::EHABILowering;
114 mlir::LogicalResult
run()
override;
119 using EhTokenMap = DenseMap<mlir::Value, std::pair<mlir::Value, mlir::Value>>;
121 cir::VoidType voidType;
122 cir::PointerType voidPtrType;
123 cir::PointerType u8PtrType;
124 cir::IntType u32Type;
125 cir::IntType s32Type;
129 cir::FuncOp personalityFunc;
130 cir::FuncOp beginCatchFunc;
131 cir::FuncOp endCatchFunc;
132 cir::FuncOp getExceptionPtrFunc;
133 cir::FuncOp clangCallTerminateFunc;
134 cir::FuncOp cxaThrowFunc;
135 cir::FuncOp cxaRethrowFunc;
136 cir::FuncOp cxaCallUnexpectedFunc;
138 DenseMap<mlir::StringAttr, cir::FuncOp> catchCopyThunks;
140 constexpr const static ::llvm::StringLiteral kGxxPersonality =
141 "__gxx_personality_v0";
143 void ensureRuntimeDecls(mlir::Location loc);
144 void ensureClangCallTerminate(mlir::Location loc);
145 void ensureCxaThrowDecl(mlir::Location loc);
146 void ensureCxaRethrowDecl(mlir::Location loc);
147 void ensureCxaCallUnexpectedDecl(mlir::Location loc);
148 mlir::Block *buildTerminateBlock(cir::FuncOp funcOp, mlir::Location loc);
149 mlir::FailureOr<cir::FuncOp>
150 resolveCatchCopyThunk(cir::ConstructCatchParamOp op);
151 mlir::LogicalResult lowerFunc(cir::FuncOp funcOp);
153 lowerEhInitiate(cir::EhInitiateOp initiateOp,
154 llvm::ArrayRef<cir::EhDispatchOp> reachedDispatches,
155 bool reachesCleanup, EhTokenMap &ehTokenMap);
156 void lowerDispatch(cir::EhDispatchOp dispatch, mlir::Value exnPtr,
158 mlir::LogicalResult lowerConstructCatchParam(cir::ConstructCatchParamOp op,
160 void lowerInitCatchParam(cir::InitCatchParamOp op);
161 mlir::LogicalResult lowerTryThrow(cir::TryThrowOp op);
165mlir::LogicalResult ItaniumEHLowering::run() {
168 voidType = cir::VoidType::get(ctx);
169 voidPtrType = cir::PointerType::get(voidType);
170 auto u8Type = cir::IntType::get(ctx, 8,
false);
171 u8PtrType = cir::PointerType::get(u8Type);
172 u32Type = cir::IntType::get(ctx, 32,
false);
173 s32Type = cir::IntType::get(ctx, 32,
true);
175 for (cir::FuncOp funcOp : mod.getOps<cir::FuncOp>()) {
176 if (mlir::failed(lowerFunc(funcOp)))
177 return mlir::failure();
179 return mlir::success();
184void ItaniumEHLowering::ensureRuntimeDecls(mlir::Location loc) {
187 if (!personalityFunc) {
188 auto personalityFuncTy = cir::FuncType::get({}, s32Type,
true);
189 personalityFunc = getOrCreateRuntimeFuncDecl(mod, loc, kGxxPersonality,
193 if (!beginCatchFunc) {
194 auto beginCatchFuncTy =
195 cir::FuncType::get({voidPtrType}, u8PtrType,
false);
196 beginCatchFunc = getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_begin_catch",
201 auto endCatchFuncTy = cir::FuncType::get({}, voidType,
false);
203 getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_end_catch", endCatchFuncTy);
206 if (!getExceptionPtrFunc) {
207 auto getExceptionPtrFuncTy =
208 cir::FuncType::get({voidPtrType}, u8PtrType,
false);
209 getExceptionPtrFunc = getOrCreateRuntimeFuncDecl(
210 mod, loc,
"__cxa_get_exception_ptr", getExceptionPtrFuncTy);
223void ItaniumEHLowering::ensureClangCallTerminate(mlir::Location loc) {
226 if (clangCallTerminateFunc)
229 ensureRuntimeDecls(loc);
231 if (
auto existing = mod.lookupSymbol<cir::FuncOp>(
"__clang_call_terminate")) {
232 clangCallTerminateFunc = existing;
236 auto funcTy = cir::FuncType::get({voidPtrType}, voidType,
false);
237 builder.setInsertionPointToEnd(mod.getBody());
239 cir::FuncOp::create(builder, loc,
"__clang_call_terminate", funcTy);
240 funcOp.setLinkage(cir::GlobalLinkageKind::LinkOnceODRLinkage);
241 funcOp.setGlobalVisibility(cir::VisibilityKind::Hidden);
243 mlir::Block *entryBlock = funcOp.addEntryBlock();
244 builder.setInsertionPointToStart(entryBlock);
245 mlir::Value exnArg = entryBlock->getArgument(0);
247 auto catchCall = cir::CallOp::create(
248 builder, loc, mlir::FlatSymbolRefAttr::get(beginCatchFunc), u8PtrType,
249 mlir::ValueRange{exnArg});
250 catchCall.setNothrowAttr(builder.getUnitAttr());
252 auto terminateFuncDecl = getOrCreateRuntimeFuncDecl(
253 mod, loc,
"_ZSt9terminatev",
254 cir::FuncType::get({}, voidType,
false));
255 terminateFuncDecl->setAttr(cir::CIRDialect::getNoReturnAttrName(),
256 builder.getUnitAttr());
257 auto terminateCall = cir::CallOp::create(
258 builder, loc, mlir::FlatSymbolRefAttr::get(terminateFuncDecl), voidType,
260 terminateCall.setNothrowAttr(builder.getUnitAttr());
261 terminateCall->setAttr(cir::CIRDialect::getNoReturnAttrName(),
262 builder.getUnitAttr());
264 cir::UnreachableOp::create(builder, loc);
266 funcOp->setAttr(cir::CIRDialect::getNoReturnAttrName(),
267 builder.getUnitAttr());
268 clangCallTerminateFunc = funcOp;
274void ItaniumEHLowering::ensureCxaThrowDecl(mlir::Location loc) {
277 auto throwFuncTy = cir::FuncType::get({voidPtrType, voidPtrType, voidPtrType},
280 getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_throw", throwFuncTy);
286void ItaniumEHLowering::ensureCxaRethrowDecl(mlir::Location loc) {
289 auto rethrowFuncTy = cir::FuncType::get({}, voidType,
false);
291 getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_rethrow", rethrowFuncTy);
295void ItaniumEHLowering::ensureCxaCallUnexpectedDecl(mlir::Location loc) {
296 if (cxaCallUnexpectedFunc)
298 auto unexpectedFuncTy =
299 cir::FuncType::get({voidPtrType}, voidType,
false);
300 cxaCallUnexpectedFunc = getOrCreateRuntimeFuncDecl(
301 mod, loc,
"__cxa_call_unexpected", unexpectedFuncTy);
305mlir::Block *ItaniumEHLowering::buildTerminateBlock(cir::FuncOp funcOp,
306 mlir::Location loc) {
309 assert(clangCallTerminateFunc &&
310 "ensureClangCallTerminate must run before buildTerminateBlock");
311 mlir::Region &body = funcOp.getRegion();
312 mlir::Block *terminateBlock = builder.createBlock(&body, body.end());
313 auto inflight = cir::EhInflightOp::create(
314 builder, loc,
false,
true,
317 auto terminateCall = cir::CallOp::create(
318 builder, loc, mlir::FlatSymbolRefAttr::get(clangCallTerminateFunc),
319 voidType, mlir::ValueRange{inflight.getExceptionPtr()});
320 terminateCall.setNothrowAttr(builder.getUnitAttr());
321 terminateCall->setAttr(cir::CIRDialect::getNoReturnAttrName(),
322 builder.getUnitAttr());
323 cir::UnreachableOp::create(builder, loc);
324 return terminateBlock;
340static void collectReachableDispatches(
341 mlir::Value rootToken,
342 llvm::SmallSetVector<cir::EhDispatchOp, 4> &dispatches,
343 bool &reachesCleanup) {
344 llvm::SmallVector<mlir::Value> worklist;
345 llvm::SmallPtrSet<mlir::Value, 8> visited;
346 worklist.push_back(rootToken);
350 for (
unsigned i = 0; i < worklist.size(); ++i) {
351 mlir::Value current = worklist[i];
352 if (!visited.insert(current).second)
354 for (mlir::OpOperand &use : current.getUses()) {
355 mlir::Operation *user = use.getOwner();
360 if (mlir::isa<cir::BeginCleanupOp>(user))
361 reachesCleanup =
true;
362 if (
auto dispatch = mlir::dyn_cast<cir::EhDispatchOp>(user))
363 dispatches.insert(dispatch);
365 for (
unsigned s = 0, e = user->getNumSuccessors(); s < e; ++s)
366 for (mlir::BlockArgument arg : user->getSuccessor(s)->getArguments())
367 if (mlir::isa<cir::EhTokenType>(
arg.getType()))
368 worklist.push_back(arg);
374mlir::LogicalResult ItaniumEHLowering::lowerFunc(cir::FuncOp funcOp) {
375 if (funcOp.isDeclaration())
376 return mlir::success();
382 SmallVector<cir::EhInitiateOp> initiateOps;
383 funcOp.walk([&](cir::EhInitiateOp op) { initiateOps.push_back(op); });
384 if (initiateOps.empty())
385 return mlir::success();
387 ensureRuntimeDecls(funcOp.getLoc());
394 if (!funcOp.getPersonality())
395 funcOp.setPersonality(kGxxPersonality);
409 struct InitiateEHInfo {
410 llvm::SmallSetVector<cir::EhDispatchOp, 4> reachedDispatches;
411 bool reachesCleanup =
false;
413 llvm::DenseMap<mlir::Operation *, InitiateEHInfo> initiateInfo;
414 llvm::SmallSetVector<cir::EhDispatchOp, 4> dispatchesToLower;
415 for (cir::EhInitiateOp initiateOp : initiateOps) {
416 InitiateEHInfo &
info = initiateInfo[initiateOp.getOperation()];
417 collectReachableDispatches(initiateOp.getEhToken(),
info.reachedDispatches,
418 info.reachesCleanup);
419 dispatchesToLower.insert(
info.reachedDispatches.begin(),
420 info.reachedDispatches.end());
423 EhTokenMap ehTokenMap;
424 for (cir::EhInitiateOp initiateOp : initiateOps) {
425 const InitiateEHInfo &
info = initiateInfo[initiateOp.getOperation()];
426 if (mlir::failed(lowerEhInitiate(initiateOp,
427 info.reachedDispatches.getArrayRef(),
428 info.reachesCleanup, ehTokenMap)))
429 return mlir::failure();
436 for (cir::EhDispatchOp dispatch : dispatchesToLower) {
437 auto [exnPtr, typeId] = ehTokenMap.lookup(dispatch.getEhToken());
438 assert(exnPtr && typeId &&
439 "dispatch eh_token must be registered in ehTokenMap");
440 lowerDispatch(dispatch, exnPtr, typeId);
445 for (mlir::Block &block : funcOp.getBody()) {
446 for (
int i = block.getNumArguments() - 1; i >= 0; --i) {
447 if (mlir::isa<cir::EhTokenType>(block.getArgument(i).getType()))
448 block.eraseArgument(i);
455 SmallVector<cir::InitCatchParamOp> initCatchOps;
456 funcOp.walk([&](cir::InitCatchParamOp op) { initCatchOps.push_back(op); });
457 for (cir::InitCatchParamOp op : initCatchOps)
458 lowerInitCatchParam(op);
463 SmallVector<cir::TryThrowOp> tryThrowOps;
464 funcOp.walk([&](cir::TryThrowOp op) { tryThrowOps.push_back(op); });
465 for (cir::TryThrowOp op : tryThrowOps)
466 if (mlir::failed(lowerTryThrow(op)))
467 return mlir::failure();
469 return mlir::success();
498mlir::LogicalResult ItaniumEHLowering::lowerEhInitiate(
499 cir::EhInitiateOp initiateOp,
500 llvm::ArrayRef<cir::EhDispatchOp> reachedDispatches,
bool reachesCleanup,
501 EhTokenMap &ehTokenMap) {
504 mlir::Value rootToken = initiateOp.getEhToken();
514 mlir::ArrayAttr catchTypeList;
515 mlir::ArrayAttr filterTypeList;
516 bool catchAll =
false;
517 SmallVector<mlir::Attribute> typeSymbols;
518 for (cir::EhDispatchOp dispatch : reachedDispatches) {
519 if (mlir::ArrayAttr catchTypes = dispatch.getCatchTypesAttr()) {
520 for (mlir::Attribute attr : catchTypes) {
521 if (
auto filter = mlir::dyn_cast<cir::EhFilterAttr>(attr)) {
522 SmallVector<mlir::Attribute> filterSymbols;
525 for (mlir::Attribute typeAttr : filter.getPermittedTypes()) {
526 auto globalView = mlir::cast<cir::GlobalViewAttr>(typeAttr);
527 filterSymbols.push_back(globalView.getSymbol());
529 filterTypeList = builder.getArrayAttr(filterSymbols);
532 typeSymbols.push_back(
533 mlir::cast<cir::GlobalViewAttr>(attr).getSymbol());
536 if (dispatch.getDefaultIsCatchAll() || filterTypeList) {
537 catchAll = dispatch.getDefaultIsCatchAll();
540 assert(dispatch == reachedDispatches.back() &&
541 "catch-all or filter must be the last reachable dispatch");
545 if (!typeSymbols.empty())
546 catchTypeList = builder.getArrayAttr(typeSymbols);
548 builder.setInsertionPoint(initiateOp);
549 auto inflightOp = cir::EhInflightOp::create(
550 builder, initiateOp.getLoc(), initiateOp.getCleanup() || reachesCleanup,
551 catchAll, catchTypeList, filterTypeList);
553 ehTokenMap[rootToken] = {inflightOp.getExceptionPtr(),
554 inflightOp.getTypeId()};
560 SmallVector<mlir::Value> worklist;
561 SmallPtrSet<mlir::Value, 8> visited;
562 worklist.push_back(rootToken);
564 while (!worklist.empty()) {
565 mlir::Value current = worklist.pop_back_val();
566 if (!visited.insert(current).second)
571 SmallVector<mlir::Operation *> users;
572 for (mlir::OpOperand &use : current.getUses())
573 users.push_back(use.getOwner());
577 for (mlir::Operation *user : users) {
583 for (
unsigned s = 0; s < user->getNumSuccessors(); ++s) {
584 mlir::Block *succ = user->getSuccessor(s);
585 for (mlir::BlockArgument arg : succ->getArguments()) {
586 if (!mlir::isa<cir::EhTokenType>(
arg.getType()))
588 if (!ehTokenMap.count(arg)) {
589 mlir::Value ptrArg = succ->addArgument(voidPtrType,
arg.getLoc());
590 mlir::Value u32Arg = succ->addArgument(u32Type,
arg.getLoc());
591 ehTokenMap[
arg] = {ptrArg, u32Arg};
593 worklist.push_back(arg);
597 if (
auto op = mlir::dyn_cast<cir::BeginCleanupOp>(user)) {
600 for (
auto &tokenUsers :
601 llvm::make_early_inc_range(op.getCleanupToken().getUses())) {
603 mlir::dyn_cast<cir::EndCleanupOp>(tokenUsers.getOwner()))
607 }
else if (
auto op = mlir::dyn_cast<cir::BeginCatchOp>(user)) {
610 for (
auto &tokenUsers :
611 llvm::make_early_inc_range(op.getCatchToken().getUses())) {
613 mlir::dyn_cast<cir::EndCatchOp>(tokenUsers.getOwner())) {
614 builder.setInsertionPoint(endOp);
615 cir::CallOp::create(builder, endOp.getLoc(),
616 mlir::FlatSymbolRefAttr::get(endCatchFunc),
617 voidType, mlir::ValueRange{});
622 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
623 builder.setInsertionPoint(op);
624 auto callOp = cir::CallOp::create(
625 builder, op.getLoc(), mlir::FlatSymbolRefAttr::get(beginCatchFunc),
626 u8PtrType, mlir::ValueRange{exnPtr});
627 mlir::Value castResult = callOp.getResult();
628 mlir::Type expectedPtrType = op.getExnPtr().getType();
629 if (castResult.getType() != expectedPtrType)
631 cir::CastOp::create(builder, op.getLoc(), expectedPtrType,
632 cir::CastKind::bitcast, callOp.getResult());
633 op.getExnPtr().replaceAllUsesWith(castResult);
635 }
else if (
auto op = mlir::dyn_cast<cir::ConstructCatchParamOp>(user)) {
636 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
637 if (mlir::failed(lowerConstructCatchParam(op, exnPtr)))
638 return mlir::failure();
639 }
else if (mlir::isa<cir::EhDispatchOp>(user)) {
645 }
else if (
auto op = mlir::dyn_cast<cir::EhTerminateOp>(user)) {
646 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
647 ensureClangCallTerminate(op.getLoc());
648 builder.setInsertionPoint(op);
649 auto call = cir::CallOp::create(
650 builder, op.getLoc(),
651 mlir::FlatSymbolRefAttr::get(clangCallTerminateFunc), voidType,
652 mlir::ValueRange{exnPtr});
653 call.setNothrowAttr(builder.getUnitAttr());
654 call->setAttr(cir::CIRDialect::getNoReturnAttrName(),
655 builder.getUnitAttr());
656 cir::UnreachableOp::create(builder, op.getLoc());
658 }
else if (
auto op = mlir::dyn_cast<cir::EhUnexpectedOp>(user)) {
659 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
660 ensureCxaCallUnexpectedDecl(op.getLoc());
661 builder.setInsertionPoint(op);
662 auto call = cir::CallOp::create(
663 builder, op.getLoc(),
664 mlir::FlatSymbolRefAttr::get(cxaCallUnexpectedFunc), voidType,
665 mlir::ValueRange{exnPtr});
666 call->setAttr(cir::CIRDialect::getNoReturnAttrName(),
667 builder.getUnitAttr());
668 cir::UnreachableOp::create(builder, op.getLoc());
670 }
else if (
auto op = mlir::dyn_cast<cir::ResumeOp>(user)) {
671 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
672 builder.setInsertionPoint(op);
673 cir::ResumeFlatOp::create(builder, op.getLoc(), exnPtr, typeId);
675 }
else if (
auto op = mlir::dyn_cast<cir::BrOp>(user)) {
677 SmallVector<mlir::Value> newOperands;
678 bool changed =
false;
679 for (mlir::Value operand : op.getDestOperands()) {
680 auto it = ehTokenMap.find(operand);
681 if (it != ehTokenMap.end()) {
682 newOperands.push_back(it->second.first);
683 newOperands.push_back(it->second.second);
686 newOperands.push_back(operand);
690 builder.setInsertionPoint(op);
691 cir::BrOp::create(builder, op.getLoc(), op.getDest(), newOperands);
699 return mlir::success();
705void ItaniumEHLowering::lowerDispatch(cir::EhDispatchOp dispatch,
706 mlir::Value exnPtr, mlir::Value typeId) {
707 mlir::Location dispLoc = dispatch.getLoc();
708 mlir::Block *defaultDest = dispatch.getDefaultDestination();
709 mlir::Block *dispatchBlock = dispatch->getBlock();
711 llvm::SmallVector<mlir::Attribute> catchAttrs;
712 llvm::SmallVector<mlir::Block *> catchDests;
713 cir::EhFilterAttr filterAttr;
714 mlir::Block *filterDest =
nullptr;
715 if (mlir::ArrayAttr catchTypes = dispatch.getCatchTypesAttr()) {
716 for (
auto [attr, dest] :
717 llvm::zip(catchTypes, dispatch.getCatchDestinations())) {
718 if (
auto filter = mlir::dyn_cast<cir::EhFilterAttr>(attr)) {
719 assert(!filterAttr &&
"at most one filter handler");
724 catchAttrs.push_back(attr);
725 catchDests.push_back(dest);
732 mlir::Block *
insertBefore = dispatchBlock->getNextNode();
733 mlir::Block *falseDest = defaultDest;
735 assert(filterDest &&
"filter handler requires a destination");
738 if (filterAttr.getPermittedTypes().empty()) {
739 falseDest = filterDest;
744 auto *cmpBlock = builder.createBlock(insertBefore, {voidPtrType, u32Type},
746 mlir::Value cmpExnPtr = cmpBlock->getArgument(0);
747 mlir::Value cmpTypeId = cmpBlock->getArgument(1);
748 mlir::Value signedTypeId = cir::CastOp::create(
749 builder, dispLoc, s32Type, cir::CastKind::integral, cmpTypeId);
750 mlir::Value zero = cir::ConstantOp::create(builder, dispLoc,
751 cir::IntAttr::get(s32Type, 0));
752 auto cmpOp = cir::CmpOp::create(builder, dispLoc, cir::CmpOpKind::lt,
754 cir::BrCondOp::create(builder, dispLoc, cmpOp, filterDest, defaultDest,
755 mlir::ValueRange{cmpExnPtr, cmpTypeId},
756 mlir::ValueRange{cmpExnPtr, cmpTypeId});
758 falseDest = cmpBlock;
762 mlir::Block *firstCmpBlock =
nullptr;
763 if (!catchAttrs.empty()) {
764 unsigned numCatches = catchAttrs.size();
765 for (
int i = numCatches - 1; i >= 0; --i) {
766 auto *cmpBlock = builder.createBlock(insertBefore, {voidPtrType, u32Type},
769 mlir::Value cmpExnPtr = cmpBlock->getArgument(0);
770 mlir::Value cmpTypeId = cmpBlock->getArgument(1);
772 auto globalView = mlir::cast<cir::GlobalViewAttr>(catchAttrs[i]);
774 cir::EhTypeIdOp::create(builder, dispLoc, globalView.getSymbol());
775 auto cmpOp = cir::CmpOp::create(builder, dispLoc, cir::CmpOpKind::eq,
776 cmpTypeId, ehTypeIdOp.getTypeId());
778 cir::BrCondOp::create(builder, dispLoc, cmpOp, catchDests[i], falseDest,
779 mlir::ValueRange{cmpExnPtr, cmpTypeId},
780 mlir::ValueRange{cmpExnPtr, cmpTypeId});
783 falseDest = cmpBlock;
784 firstCmpBlock = cmpBlock;
787 firstCmpBlock = falseDest;
790 builder.setInsertionPoint(dispatch);
791 cir::BrOp::create(builder, dispLoc, firstCmpBlock,
792 mlir::ValueRange{exnPtr, typeId});
799mlir::FailureOr<cir::FuncOp>
800ItaniumEHLowering::resolveCatchCopyThunk(cir::ConstructCatchParamOp op) {
801 mlir::FlatSymbolRefAttr thunkRef = op.getCopyFnAttr();
802 mlir::StringAttr thunkName = thunkRef.getAttr();
803 auto cached = catchCopyThunks.find(thunkName);
804 if (cached != catchCopyThunks.end())
805 return cached->second;
807 cir::FuncOp thunk = mod.lookupSymbol<cir::FuncOp>(thunkRef);
809 return op.emitError(
"could not resolve catch-copy thunk symbol");
810 assert(thunk->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()) &&
811 "verifier should have rejected non-thunk catch-copy reference");
812 if (thunk.isDeclaration())
813 return op.emitError(
"catch-copy thunk has no body to inline");
815 mlir::Region &thunkRegion = thunk.getRegion();
816 if (!llvm::hasSingleElement(thunkRegion))
817 return op.emitError(
"multi-block catch-copy thunks are NYI");
819 mlir::Block &thunkEntry = thunkRegion.front();
820 assert(thunkEntry.getNumArguments() == 2 &&
821 "catch-copy thunk must have exactly two parameters");
822 if (!mlir::isa<cir::ReturnOp>(thunkEntry.getTerminator()))
823 return op.emitError(
"catch-copy thunk must end in cir.return");
825 catchCopyThunks[thunkName] = thunk;
833ItaniumEHLowering::lowerConstructCatchParam(cir::ConstructCatchParamOp op,
834 mlir::Value exnPtr) {
837 mlir::Location loc = op.getLoc();
838 mlir::Value paramAddr = op.getParamAddr();
839 cir::PointerType paramAddrType =
840 mlir::cast<cir::PointerType>(paramAddr.getType());
842 if (op.getKind() == cir::InitCatchKind::ReferenceToPointer) {
844 constexpr unsigned headerSize = 32;
846 builder.setInsertionPoint(op);
847 auto index = cir::ConstantOp::create(
848 builder, loc, cir::IntAttr::get(u32Type, headerSize));
849 assert((exnPtr.getType() == voidPtrType || exnPtr.getType() == u8PtrType) &&
850 "lowerConstructCatchParam exn ptr not void* or i8*");
852 cir::PtrStrideOp::create(builder, loc, exnPtr.getType(), exnPtr, index);
854 cir::CastOp::create(builder, loc, paramAddrType.getPointee(),
855 cir::CastKind::bitcast, exnObj);
856 cir::StoreOp::create(builder, loc, casted, paramAddr, {}, {}, {}, {}, {});
861 if (op.getKind() != cir::InitCatchKind::NonTrivialCopy)
862 return op.emitOpError(
"only reference_to_pointer and non_trivial_copy "
863 "kinds are supported");
865 ensureRuntimeDecls(loc);
866 ensureClangCallTerminate(loc);
869 builder.setInsertionPoint(op);
870 cir::CallOp getExnCall = cir::CallOp::create(
871 builder, loc, mlir::FlatSymbolRefAttr::get(getExceptionPtrFunc),
872 u8PtrType, mlir::ValueRange{exnPtr});
873 getExnCall.setNothrowAttr(builder.getUnitAttr());
874 mlir::Value adjusted =
875 cir::CastOp::create(builder, loc, paramAddrType, cir::CastKind::bitcast,
876 getExnCall.getResult());
879 mlir::FailureOr<cir::FuncOp> thunkOr = resolveCatchCopyThunk(op);
880 if (mlir::failed(thunkOr))
881 return mlir::failure();
882 cir::FuncOp thunk = *thunkOr;
886 assert(llvm::hasSingleElement(thunk.getRegion()) &&
887 "multi-block catch-copy thunks are NYI");
890 mlir::Block &thunkEntry = thunk.getRegion().front();
891 mlir::IRMapping mapping;
892 mapping.map(thunkEntry.getArgument(0), paramAddr);
893 mapping.map(thunkEntry.getArgument(1), adjusted);
894 llvm::SmallVector<cir::CallOp> throwingCalls;
895 for (mlir::Operation &thunkOp : thunkEntry.without_terminator()) {
896 mlir::Operation *cloned = builder.clone(thunkOp, mapping);
897 if (cir::CallOp callOp = mlir::dyn_cast<cir::CallOp>(cloned))
898 if (!callOp.getNothrow())
899 throwingCalls.push_back(callOp);
903 if (throwingCalls.empty())
904 return mlir::success();
908 mlir::IRRewriter rewriter(builder);
909 mlir::Block *terminateBlock =
nullptr;
910 for (cir::CallOp call : throwingCalls) {
912 terminateBlock = buildTerminateBlock(call->getParentOfType<cir::FuncOp>(),
916 return mlir::success();
923mlir::LogicalResult ItaniumEHLowering::lowerTryThrow(cir::TryThrowOp op) {
926 mlir::Location loc = op.getLoc();
927 mlir::Block *normalDest = op.getNormalDest();
928 mlir::Block *unwindDest = op.getUnwindDest();
929 builder.setInsertionPoint(op);
932 ensureCxaRethrowDecl(loc);
933 cir::TryCallOp::create(
934 builder, loc, mlir::FlatSymbolRefAttr::get(cxaRethrowFunc), voidType,
935 normalDest, unwindDest, mlir::ValueRange{});
937 return mlir::success();
940 ensureCxaThrowDecl(loc);
943 mlir::Value exnPtr = op.getExceptionPtr();
944 if (exnPtr.getType() != voidPtrType)
945 exnPtr = cir::CastOp::create(builder, loc, voidPtrType,
946 cir::CastKind::bitcast, exnPtr);
951 mlir::FlatSymbolRefAttr typeInfoAttr = op.getTypeInfoAttr();
952 auto typeInfoGlobal = mod.lookupSymbol<cir::GlobalOp>(typeInfoAttr);
954 return op.emitError(
"type_info symbol not found in module");
955 auto typeInfoPtrTy = cir::PointerType::get(typeInfoGlobal.getSymType());
956 mlir::Value typeInfo = cir::GetGlobalOp::create(builder, loc, typeInfoPtrTy,
957 typeInfoAttr.getValue());
958 if (typeInfo.getType() != voidPtrType)
959 typeInfo = cir::CastOp::create(builder, loc, voidPtrType,
960 cir::CastKind::bitcast, typeInfo);
964 if (mlir::FlatSymbolRefAttr dtorAttr = op.getDtorAttr()) {
965 auto dtorFunc = mod.lookupSymbol<cir::FuncOp>(dtorAttr);
967 return op.emitError(
"dtor symbol not found in module");
968 auto dtorPtrTy = cir::PointerType::get(dtorFunc.getFunctionType());
970 cir::GetGlobalOp::create(builder, loc, dtorPtrTy, dtorAttr.getValue());
971 if (dtor.getType() != voidPtrType)
972 dtor = cir::CastOp::create(builder, loc, voidPtrType,
973 cir::CastKind::bitcast, dtor);
975 dtor = cir::ConstantOp::create(
977 cir::ConstPtrAttr::get(voidPtrType, builder.getI64IntegerAttr(0)));
980 cir::TryCallOp::create(
981 builder, loc, mlir::FlatSymbolRefAttr::get(cxaThrowFunc), voidType,
982 normalDest, unwindDest, mlir::ValueRange{exnPtr, typeInfo, dtor});
984 return mlir::success();
1012void ItaniumEHLowering::lowerInitCatchParam(cir::InitCatchParamOp op) {
1013 builder.setInsertionPoint(op);
1014 mlir::Location loc = op.getLoc();
1015 mlir::Value exnPtr = op.getExnPtr();
1016 mlir::Value paramAddr = op.getParamAddr();
1017 auto paramAddrType = mlir::cast<cir::PointerType>(paramAddr.getType());
1018 mlir::Type elementType = paramAddrType.getPointee();
1019 cir::InitCatchKind
kind = op.getKind();
1022 case InitCatchKind::Reference: {
1023 mlir::Value casted = cir::CastOp::create(builder, loc, elementType,
1024 cir::CastKind::bitcast, exnPtr);
1025 cir::StoreOp::create(builder, loc, casted, paramAddr, {}, {}, {}, {}, {});
1028 case InitCatchKind::ReferenceToPointer:
1032 case InitCatchKind::ReferenceToRecordPointer: {
1038 auto caughtType = mlir::cast<cir::PointerType>(
1039 mlir::cast<cir::PointerType>(elementType).getPointee());
1040 cir::AllocaOp byRefTmp;
1042 mlir::OpBuilder::InsertionGuard guard(builder);
1043 builder.setInsertionPointToStart(
1044 &op->getParentOfType<cir::FuncOp>().getBody().front());
1045 cir::CIRDataLayout dataLayout(mod);
1047 dataLayout.getAlignment(caughtType,
true).value();
1049 cir::AllocaOp::create(builder, loc, elementType,
"exn.byref.tmp",
1050 builder.getI64IntegerAttr(alignment));
1052 mlir::Value casted = cir::CastOp::create(builder, loc, caughtType,
1053 cir::CastKind::bitcast, exnPtr);
1054 cir::StoreOp::create(builder, loc, casted, byRefTmp, {}, {}, {}, {}, {});
1055 cir::StoreOp::create(builder, loc, byRefTmp, paramAddr, {}, {}, {}, {}, {});
1058 case InitCatchKind::TrivialCopy: {
1059 mlir::Value srcPtr = cir::CastOp::create(builder, loc, paramAddrType,
1060 cir::CastKind::bitcast, exnPtr);
1061 cir::CopyOp::create(builder, loc, paramAddr, srcPtr, {}, {});
1064 case InitCatchKind::NonTrivialCopy:
1068 case InitCatchKind::Scalar: {
1072 mlir::Value srcPtr = cir::CastOp::create(builder, loc, paramAddrType,
1073 cir::CastKind::bitcast, exnPtr);
1074 auto loadOp = cir::LoadOp::create(builder, loc, elementType, srcPtr);
1075 cir::StoreOp::create(builder, loc, loadOp.getResult(), paramAddr, {}, {},
1079 case InitCatchKind::Pointer: {
1080 mlir::Value casted = cir::CastOp::create(builder, loc, elementType,
1081 cir::CastKind::bitcast, exnPtr);
1082 cir::StoreOp::create(builder, loc, casted, paramAddr, {}, {}, {}, {}, {});
1085 case InitCatchKind::Objc:
1086 llvm_unreachable(
"InitCatchParam: ObjCLifetime is NYI");
1097struct CIREHABILoweringPass
1098 :
public impl::CIREHABILoweringBase<CIREHABILoweringPass> {
1099 CIREHABILoweringPass() =
default;
1100 void runOnOperation()
override;
1106static void eraseCatchCopyThunks(mlir::ModuleOp mod) {
1107 llvm::StringRef catchHelperAttr =
1108 cir::CIRDialect::getCatchCopyThunkAttrName();
1109 for (cir::FuncOp f : llvm::make_early_inc_range(mod.getOps<cir::FuncOp>())) {
1110 if (!f->hasAttr(catchHelperAttr))
1114 assert(mlir::SymbolTable::symbolKnownUseEmpty(f, mod) &&
1115 "catch-init helper has remaining users");
1120void CIREHABILoweringPass::runOnOperation() {
1121 auto mod = mlir::cast<mlir::ModuleOp>(getOperation());
1126 auto tripleAttr = mlir::dyn_cast_if_present<mlir::StringAttr>(
1127 mod->getAttr(cir::CIRDialect::getTripleAttrName()));
1129 mod.emitError(
"Module has no target triple");
1136 llvm::Triple triple(tripleAttr.getValue());
1137 std::unique_ptr<EHABILowering> lowering;
1138 if (triple.isWindowsMSVCEnvironment()) {
1140 "EH ABI lowering is not yet implemented for the Microsoft ABI");
1141 return signalPassFailure();
1143 lowering = std::make_unique<ItaniumEHLowering>(mod);
1146 if (mlir::failed(lowering->run()))
1147 return signalPassFailure();
1150 eraseCatchCopyThunks(mod);
1156 return std::make_unique<CIREHABILoweringPass>();
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
mlir::Block * replaceCallWithTryCall(cir::CallOp callOp, mlir::Block *unwindDest, mlir::Location loc, mlir::RewriterBase &rewriter)
Replace a cir::CallOp with a cir::TryCallOp whose unwind destination is unwindDest.
void info(bool Verbose, unsigned Level, const char *Fmt, Ts &&...Args)
Prints an indented note to stderr when Verbose is set.
std::unique_ptr< Pass > createCIREHABILoweringPass()
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
static bool opFuncCallingConv()
static bool sizeOfUnwindException()