34#include "mlir/IR/Builders.h"
35#include "mlir/IR/IRMapping.h"
36#include "mlir/IR/PatternMatch.h"
44#include "llvm/ADT/DenseMap.h"
45#include "llvm/ADT/SetVector.h"
46#include "llvm/ADT/SmallVector.h"
47#include "llvm/TargetParser/Triple.h"
53#define GEN_PASS_DEF_CIREHABILOWERING
54#include "clang/CIR/Dialect/Passes.h.inc"
65static cir::FuncOp getOrCreateRuntimeFuncDecl(mlir::ModuleOp mod,
68 cir::FuncType funcTy) {
69 if (
auto existing = mod.lookupSymbol<cir::FuncOp>(
name))
72 mlir::OpBuilder builder(mod.getContext());
73 builder.setInsertionPointToEnd(mod.getBody());
74 auto funcOp = cir::FuncOp::create(builder, loc,
name, funcTy);
75 funcOp.setLinkage(cir::GlobalLinkageKind::ExternalLinkage);
77 funcOp->setAttr(cir::CIRDialect::getRuntimeFuncAttrName(),
78 builder.getUnitAttr());
81 funcOp.setRequiresCallConvLowering(
false);
93 explicit EHABILowering(mlir::ModuleOp mod)
94 : mod(mod), ctx(mod.getContext()), builder(ctx) {}
95 virtual ~EHABILowering() =
default;
98 virtual mlir::LogicalResult
run() = 0;
102 mlir::MLIRContext *ctx;
103 mlir::OpBuilder builder;
117class ItaniumEHLowering :
public EHABILowering {
119 using EHABILowering::EHABILowering;
120 mlir::LogicalResult
run()
override;
125 using EhTokenMap = DenseMap<mlir::Value, std::pair<mlir::Value, mlir::Value>>;
127 cir::VoidType voidType;
128 cir::PointerType voidPtrType;
129 cir::PointerType u8PtrType;
130 cir::IntType u32Type;
131 cir::IntType s32Type;
135 cir::FuncOp personalityFunc;
136 cir::FuncOp beginCatchFunc;
137 cir::FuncOp endCatchFunc;
138 cir::FuncOp getExceptionPtrFunc;
139 cir::FuncOp clangCallTerminateFunc;
140 cir::FuncOp cxaThrowFunc;
141 cir::FuncOp cxaRethrowFunc;
142 cir::FuncOp cxaCallUnexpectedFunc;
144 DenseMap<mlir::StringAttr, cir::FuncOp> catchCopyThunks;
146 llvm::SmallSetVector<mlir::StringAttr, 1> droppedPersonalities;
148 constexpr const static ::llvm::StringLiteral kGxxPersonality =
149 "__gxx_personality_v0";
151 void ensureRuntimeDecls(mlir::Location loc);
152 void ensureClangCallTerminate(mlir::Location loc);
153 void ensureCxaThrowDecl(mlir::Location loc);
154 void ensureCxaRethrowDecl(mlir::Location loc);
155 void ensureCxaCallUnexpectedDecl(mlir::Location loc);
156 mlir::Block *buildTerminateBlock(cir::FuncOp funcOp, mlir::Location loc);
157 mlir::FailureOr<cir::FuncOp>
158 resolveCatchCopyThunk(cir::ConstructCatchParamOp op);
159 mlir::LogicalResult lowerFunc(cir::FuncOp funcOp);
161 lowerEhInitiate(cir::EhInitiateOp initiateOp,
162 llvm::ArrayRef<cir::EhDispatchOp> reachedDispatches,
163 bool reachesCleanup, EhTokenMap &ehTokenMap);
164 void lowerDispatch(cir::EhDispatchOp dispatch, mlir::Value exnPtr,
166 mlir::LogicalResult lowerConstructCatchParam(cir::ConstructCatchParamOp op,
168 void lowerInitCatchParam(cir::InitCatchParamOp op);
169 mlir::LogicalResult lowerTryThrow(cir::TryThrowOp op);
173mlir::LogicalResult ItaniumEHLowering::run() {
176 voidType = cir::VoidType::get(ctx);
177 voidPtrType = cir::PointerType::get(voidType);
178 auto u8Type = cir::IntType::get(ctx, 8,
false);
179 u8PtrType = cir::PointerType::get(u8Type);
180 u32Type = cir::IntType::get(ctx, 32,
false);
181 s32Type = cir::IntType::get(ctx, 32,
true);
183 for (cir::FuncOp funcOp : mod.getOps<cir::FuncOp>()) {
184 if (mlir::failed(lowerFunc(funcOp)))
185 return mlir::failure();
188 for (mlir::StringAttr name : droppedPersonalities) {
189 auto personalityDecl = mod.lookupSymbol<cir::FuncOp>(
name);
190 if (personalityDecl && personalityDecl.isDeclaration() &&
191 mlir::SymbolTable::symbolKnownUseEmpty(personalityDecl, mod))
192 personalityDecl.erase();
194 return mlir::success();
199void ItaniumEHLowering::ensureRuntimeDecls(mlir::Location loc) {
202 if (!personalityFunc) {
203 auto personalityFuncTy = cir::FuncType::get({}, s32Type,
true);
204 personalityFunc = getOrCreateRuntimeFuncDecl(mod, loc, kGxxPersonality,
208 if (!beginCatchFunc) {
209 auto beginCatchFuncTy =
210 cir::FuncType::get({voidPtrType}, u8PtrType,
false);
211 beginCatchFunc = getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_begin_catch",
216 auto endCatchFuncTy = cir::FuncType::get({}, voidType,
false);
218 getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_end_catch", endCatchFuncTy);
221 if (!getExceptionPtrFunc) {
222 auto getExceptionPtrFuncTy =
223 cir::FuncType::get({voidPtrType}, u8PtrType,
false);
224 getExceptionPtrFunc = getOrCreateRuntimeFuncDecl(
225 mod, loc,
"__cxa_get_exception_ptr", getExceptionPtrFuncTy);
238void ItaniumEHLowering::ensureClangCallTerminate(mlir::Location loc) {
241 if (clangCallTerminateFunc)
244 ensureRuntimeDecls(loc);
246 if (
auto existing = mod.lookupSymbol<cir::FuncOp>(
"__clang_call_terminate")) {
247 clangCallTerminateFunc = existing;
251 auto funcTy = cir::FuncType::get({voidPtrType}, voidType,
false);
252 builder.setInsertionPointToEnd(mod.getBody());
254 cir::FuncOp::create(builder, loc,
"__clang_call_terminate", funcTy);
255 funcOp.setLinkage(cir::GlobalLinkageKind::LinkOnceODRLinkage);
256 funcOp.setGlobalVisibility(cir::VisibilityKind::Hidden);
259 funcOp.setRequiresCallConvLowering(
false);
261 mlir::Block *entryBlock = funcOp.addEntryBlock();
262 builder.setInsertionPointToStart(entryBlock);
263 mlir::Value exnArg = entryBlock->getArgument(0);
265 auto catchCall = cir::CallOp::create(
266 builder, loc, mlir::FlatSymbolRefAttr::get(beginCatchFunc), u8PtrType,
267 mlir::ValueRange{exnArg});
268 catchCall.setNothrowAttr(builder.getUnitAttr());
270 auto terminateFuncDecl = getOrCreateRuntimeFuncDecl(
271 mod, loc,
"_ZSt9terminatev",
272 cir::FuncType::get({}, voidType,
false));
273 terminateFuncDecl->setAttr(cir::CIRDialect::getNoReturnAttrName(),
274 builder.getUnitAttr());
275 auto terminateCall = cir::CallOp::create(
276 builder, loc, mlir::FlatSymbolRefAttr::get(terminateFuncDecl), voidType,
278 terminateCall.setNothrowAttr(builder.getUnitAttr());
279 terminateCall->setAttr(cir::CIRDialect::getNoReturnAttrName(),
280 builder.getUnitAttr());
282 cir::UnreachableOp::create(builder, loc);
284 funcOp->setAttr(cir::CIRDialect::getNoReturnAttrName(),
285 builder.getUnitAttr());
286 clangCallTerminateFunc = funcOp;
292void ItaniumEHLowering::ensureCxaThrowDecl(mlir::Location loc) {
295 auto throwFuncTy = cir::FuncType::get({voidPtrType, voidPtrType, voidPtrType},
298 getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_throw", throwFuncTy);
304void ItaniumEHLowering::ensureCxaRethrowDecl(mlir::Location loc) {
307 auto rethrowFuncTy = cir::FuncType::get({}, voidType,
false);
309 getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_rethrow", rethrowFuncTy);
313void ItaniumEHLowering::ensureCxaCallUnexpectedDecl(mlir::Location loc) {
314 if (cxaCallUnexpectedFunc)
316 auto unexpectedFuncTy =
317 cir::FuncType::get({voidPtrType}, voidType,
false);
318 cxaCallUnexpectedFunc = getOrCreateRuntimeFuncDecl(
319 mod, loc,
"__cxa_call_unexpected", unexpectedFuncTy);
323mlir::Block *ItaniumEHLowering::buildTerminateBlock(cir::FuncOp funcOp,
324 mlir::Location loc) {
327 assert(clangCallTerminateFunc &&
328 "ensureClangCallTerminate must run before buildTerminateBlock");
329 mlir::Region &body = funcOp.getRegion();
330 mlir::Block *terminateBlock = builder.createBlock(&body, body.end());
331 auto inflight = cir::EhInflightOp::create(
332 builder, loc,
false,
true,
335 auto terminateCall = cir::CallOp::create(
336 builder, loc, mlir::FlatSymbolRefAttr::get(clangCallTerminateFunc),
337 voidType, mlir::ValueRange{inflight.getExceptionPtr()});
338 terminateCall.setNothrowAttr(builder.getUnitAttr());
339 terminateCall->setAttr(cir::CIRDialect::getNoReturnAttrName(),
340 builder.getUnitAttr());
341 cir::UnreachableOp::create(builder, loc);
342 return terminateBlock;
358static void collectReachableDispatches(
359 mlir::Value rootToken,
360 llvm::SmallSetVector<cir::EhDispatchOp, 4> &dispatches,
361 bool &reachesCleanup) {
362 llvm::SmallVector<mlir::Value> worklist;
363 llvm::SmallPtrSet<mlir::Value, 8> visited;
364 worklist.push_back(rootToken);
368 for (
unsigned i = 0; i < worklist.size(); ++i) {
369 mlir::Value current = worklist[i];
370 if (!visited.insert(current).second)
372 for (mlir::OpOperand &use : current.getUses()) {
373 mlir::Operation *user = use.getOwner();
378 if (mlir::isa<cir::BeginCleanupOp>(user))
379 reachesCleanup =
true;
380 if (
auto dispatch = mlir::dyn_cast<cir::EhDispatchOp>(user))
381 dispatches.insert(dispatch);
383 for (
unsigned s = 0, e = user->getNumSuccessors(); s < e; ++s)
384 for (mlir::BlockArgument arg : user->getSuccessor(s)->getArguments())
385 if (mlir::isa<cir::EhTokenType>(
arg.getType()))
386 worklist.push_back(arg);
392mlir::LogicalResult ItaniumEHLowering::lowerFunc(cir::FuncOp funcOp) {
393 if (funcOp.isDeclaration())
394 return mlir::success();
400 SmallVector<cir::EhInitiateOp> initiateOps;
401 bool hasLandingPad =
false;
402 funcOp.walk([&](mlir::Operation *op) {
403 if (
auto initiateOp = mlir::dyn_cast<cir::EhInitiateOp>(op))
404 initiateOps.push_back(initiateOp);
405 else if (mlir::isa<cir::EhInflightOp>(op))
406 hasLandingPad =
true;
408 if (initiateOps.empty()) {
410 mlir::FlatSymbolRefAttr personality = funcOp.getPersonalityAttr();
411 if (personality && !hasLandingPad) {
412 droppedPersonalities.insert(personality.getAttr());
413 funcOp.removePersonalityAttr();
415 return mlir::success();
418 ensureRuntimeDecls(funcOp.getLoc());
425 if (!funcOp.getPersonality())
426 funcOp.setPersonality(kGxxPersonality);
440 struct InitiateEHInfo {
441 llvm::SmallSetVector<cir::EhDispatchOp, 4> reachedDispatches;
442 bool reachesCleanup =
false;
444 llvm::DenseMap<mlir::Operation *, InitiateEHInfo> initiateInfo;
445 llvm::SmallSetVector<cir::EhDispatchOp, 4> dispatchesToLower;
446 for (cir::EhInitiateOp initiateOp : initiateOps) {
447 InitiateEHInfo &
info = initiateInfo[initiateOp.getOperation()];
448 collectReachableDispatches(initiateOp.getEhToken(),
info.reachedDispatches,
449 info.reachesCleanup);
450 dispatchesToLower.insert(
info.reachedDispatches.begin(),
451 info.reachedDispatches.end());
454 EhTokenMap ehTokenMap;
455 for (cir::EhInitiateOp initiateOp : initiateOps) {
456 const InitiateEHInfo &
info = initiateInfo[initiateOp.getOperation()];
457 if (mlir::failed(lowerEhInitiate(initiateOp,
458 info.reachedDispatches.getArrayRef(),
459 info.reachesCleanup, ehTokenMap)))
460 return mlir::failure();
467 for (cir::EhDispatchOp dispatch : dispatchesToLower) {
468 auto [exnPtr, typeId] = ehTokenMap.lookup(dispatch.getEhToken());
469 assert(exnPtr && typeId &&
470 "dispatch eh_token must be registered in ehTokenMap");
471 lowerDispatch(dispatch, exnPtr, typeId);
476 for (mlir::Block &block : funcOp.getBody()) {
477 for (
int i = block.getNumArguments() - 1; i >= 0; --i) {
478 if (mlir::isa<cir::EhTokenType>(block.getArgument(i).getType()))
479 block.eraseArgument(i);
486 SmallVector<cir::InitCatchParamOp> initCatchOps;
487 funcOp.walk([&](cir::InitCatchParamOp op) { initCatchOps.push_back(op); });
488 for (cir::InitCatchParamOp op : initCatchOps)
489 lowerInitCatchParam(op);
494 SmallVector<cir::TryThrowOp> tryThrowOps;
495 funcOp.walk([&](cir::TryThrowOp op) { tryThrowOps.push_back(op); });
496 for (cir::TryThrowOp op : tryThrowOps)
497 if (mlir::failed(lowerTryThrow(op)))
498 return mlir::failure();
500 return mlir::success();
529mlir::LogicalResult ItaniumEHLowering::lowerEhInitiate(
530 cir::EhInitiateOp initiateOp,
531 llvm::ArrayRef<cir::EhDispatchOp> reachedDispatches,
bool reachesCleanup,
532 EhTokenMap &ehTokenMap) {
535 mlir::Value rootToken = initiateOp.getEhToken();
545 mlir::ArrayAttr catchTypeList;
546 mlir::ArrayAttr filterTypeList;
547 bool catchAll =
false;
548 SmallVector<mlir::Attribute> typeSymbols;
549 for (cir::EhDispatchOp dispatch : reachedDispatches) {
550 if (mlir::ArrayAttr catchTypes = dispatch.getCatchTypesAttr()) {
551 for (mlir::Attribute attr : catchTypes) {
552 if (
auto filter = mlir::dyn_cast<cir::EhFilterAttr>(attr)) {
553 SmallVector<mlir::Attribute> filterSymbols;
556 for (mlir::Attribute typeAttr : filter.getPermittedTypes()) {
557 auto globalView = mlir::cast<cir::GlobalViewAttr>(typeAttr);
558 filterSymbols.push_back(globalView.getSymbol());
560 filterTypeList = builder.getArrayAttr(filterSymbols);
563 typeSymbols.push_back(
564 mlir::cast<cir::GlobalViewAttr>(attr).getSymbol());
567 if (dispatch.getDefaultIsCatchAll() || filterTypeList) {
568 catchAll = dispatch.getDefaultIsCatchAll();
571 assert(dispatch == reachedDispatches.back() &&
572 "catch-all or filter must be the last reachable dispatch");
576 if (!typeSymbols.empty())
577 catchTypeList = builder.getArrayAttr(typeSymbols);
579 builder.setInsertionPoint(initiateOp);
580 auto inflightOp = cir::EhInflightOp::create(
581 builder, initiateOp.getLoc(), initiateOp.getCleanup() || reachesCleanup,
582 catchAll, catchTypeList, filterTypeList);
584 ehTokenMap[rootToken] = {inflightOp.getExceptionPtr(),
585 inflightOp.getTypeId()};
591 SmallVector<mlir::Value> worklist;
592 SmallPtrSet<mlir::Value, 8> visited;
593 worklist.push_back(rootToken);
595 while (!worklist.empty()) {
596 mlir::Value current = worklist.pop_back_val();
597 if (!visited.insert(current).second)
602 SmallVector<mlir::Operation *> users;
603 for (mlir::OpOperand &use : current.getUses())
604 users.push_back(use.getOwner());
608 for (mlir::Operation *user : users) {
614 for (
unsigned s = 0; s < user->getNumSuccessors(); ++s) {
615 mlir::Block *succ = user->getSuccessor(s);
616 for (mlir::BlockArgument arg : succ->getArguments()) {
617 if (!mlir::isa<cir::EhTokenType>(
arg.getType()))
619 if (!ehTokenMap.count(arg)) {
620 mlir::Value ptrArg = succ->addArgument(voidPtrType,
arg.getLoc());
621 mlir::Value u32Arg = succ->addArgument(u32Type,
arg.getLoc());
622 ehTokenMap[
arg] = {ptrArg, u32Arg};
624 worklist.push_back(arg);
628 if (
auto op = mlir::dyn_cast<cir::BeginCleanupOp>(user)) {
631 for (
auto &tokenUsers :
632 llvm::make_early_inc_range(op.getCleanupToken().getUses())) {
634 mlir::dyn_cast<cir::EndCleanupOp>(tokenUsers.getOwner()))
638 }
else if (
auto op = mlir::dyn_cast<cir::BeginCatchOp>(user)) {
641 for (
auto &tokenUsers :
642 llvm::make_early_inc_range(op.getCatchToken().getUses())) {
644 mlir::dyn_cast<cir::EndCatchOp>(tokenUsers.getOwner())) {
645 builder.setInsertionPoint(endOp);
646 cir::CallOp::create(builder, endOp.getLoc(),
647 mlir::FlatSymbolRefAttr::get(endCatchFunc),
648 voidType, mlir::ValueRange{});
653 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
654 builder.setInsertionPoint(op);
655 auto callOp = cir::CallOp::create(
656 builder, op.getLoc(), mlir::FlatSymbolRefAttr::get(beginCatchFunc),
657 u8PtrType, mlir::ValueRange{exnPtr});
658 mlir::Value castResult = callOp.getResult();
659 mlir::Type expectedPtrType = op.getExnPtr().getType();
660 if (castResult.getType() != expectedPtrType)
662 cir::CastOp::create(builder, op.getLoc(), expectedPtrType,
663 cir::CastKind::bitcast, callOp.getResult());
664 op.getExnPtr().replaceAllUsesWith(castResult);
666 }
else if (
auto op = mlir::dyn_cast<cir::ConstructCatchParamOp>(user)) {
667 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
668 if (mlir::failed(lowerConstructCatchParam(op, exnPtr)))
669 return mlir::failure();
670 }
else if (mlir::isa<cir::EhDispatchOp>(user)) {
676 }
else if (
auto op = mlir::dyn_cast<cir::EhTerminateOp>(user)) {
677 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
678 ensureClangCallTerminate(op.getLoc());
679 builder.setInsertionPoint(op);
680 auto call = cir::CallOp::create(
681 builder, op.getLoc(),
682 mlir::FlatSymbolRefAttr::get(clangCallTerminateFunc), voidType,
683 mlir::ValueRange{exnPtr});
684 call.setNothrowAttr(builder.getUnitAttr());
685 call->setAttr(cir::CIRDialect::getNoReturnAttrName(),
686 builder.getUnitAttr());
687 cir::UnreachableOp::create(builder, op.getLoc());
689 }
else if (
auto op = mlir::dyn_cast<cir::EhUnexpectedOp>(user)) {
690 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
691 ensureCxaCallUnexpectedDecl(op.getLoc());
692 builder.setInsertionPoint(op);
693 auto call = cir::CallOp::create(
694 builder, op.getLoc(),
695 mlir::FlatSymbolRefAttr::get(cxaCallUnexpectedFunc), voidType,
696 mlir::ValueRange{exnPtr});
697 call->setAttr(cir::CIRDialect::getNoReturnAttrName(),
698 builder.getUnitAttr());
699 cir::UnreachableOp::create(builder, op.getLoc());
701 }
else if (
auto op = mlir::dyn_cast<cir::ResumeOp>(user)) {
702 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
703 builder.setInsertionPoint(op);
704 cir::ResumeFlatOp::create(builder, op.getLoc(), exnPtr, typeId);
706 }
else if (
auto op = mlir::dyn_cast<cir::BrOp>(user)) {
708 SmallVector<mlir::Value> newOperands;
709 bool changed =
false;
710 for (mlir::Value operand : op.getDestOperands()) {
711 auto it = ehTokenMap.find(operand);
712 if (it != ehTokenMap.end()) {
713 newOperands.push_back(it->second.first);
714 newOperands.push_back(it->second.second);
717 newOperands.push_back(operand);
721 builder.setInsertionPoint(op);
723 assert(!op.getLoopIdAttr() && !op.getLoopHintsAttr());
724 cir::BrOp::create(builder, op.getLoc(), newOperands,
734 return mlir::success();
740void ItaniumEHLowering::lowerDispatch(cir::EhDispatchOp dispatch,
741 mlir::Value exnPtr, mlir::Value typeId) {
742 mlir::Location dispLoc = dispatch.getLoc();
743 mlir::Block *defaultDest = dispatch.getDefaultDestination();
744 mlir::Block *dispatchBlock = dispatch->getBlock();
746 llvm::SmallVector<mlir::Attribute> catchAttrs;
747 llvm::SmallVector<mlir::Block *> catchDests;
748 cir::EhFilterAttr filterAttr;
749 mlir::Block *filterDest =
nullptr;
750 if (mlir::ArrayAttr catchTypes = dispatch.getCatchTypesAttr()) {
751 for (
auto [attr, dest] :
752 llvm::zip(catchTypes, dispatch.getCatchDestinations())) {
753 if (
auto filter = mlir::dyn_cast<cir::EhFilterAttr>(attr)) {
754 assert(!filterAttr &&
"at most one filter handler");
759 catchAttrs.push_back(attr);
760 catchDests.push_back(dest);
767 mlir::Block *
insertBefore = dispatchBlock->getNextNode();
768 mlir::Block *falseDest = defaultDest;
770 assert(filterDest &&
"filter handler requires a destination");
773 if (filterAttr.getPermittedTypes().empty()) {
774 falseDest = filterDest;
779 auto *cmpBlock = builder.createBlock(insertBefore, {voidPtrType, u32Type},
781 mlir::Value cmpExnPtr = cmpBlock->getArgument(0);
782 mlir::Value cmpTypeId = cmpBlock->getArgument(1);
783 mlir::Value signedTypeId = cir::CastOp::create(
784 builder, dispLoc, s32Type, cir::CastKind::integral, cmpTypeId);
785 mlir::Value zero = cir::ConstantOp::create(builder, dispLoc,
786 cir::IntAttr::get(s32Type, 0));
787 auto cmpOp = cir::CmpOp::create(builder, dispLoc, cir::CmpOpKind::lt,
789 cir::BrCondOp::create(builder, dispLoc, cmpOp, filterDest, defaultDest,
790 mlir::ValueRange{cmpExnPtr, cmpTypeId},
791 mlir::ValueRange{cmpExnPtr, cmpTypeId});
793 falseDest = cmpBlock;
797 mlir::Block *firstCmpBlock =
nullptr;
798 if (!catchAttrs.empty()) {
799 unsigned numCatches = catchAttrs.size();
800 for (
int i = numCatches - 1; i >= 0; --i) {
801 auto *cmpBlock = builder.createBlock(insertBefore, {voidPtrType, u32Type},
804 mlir::Value cmpExnPtr = cmpBlock->getArgument(0);
805 mlir::Value cmpTypeId = cmpBlock->getArgument(1);
807 auto globalView = mlir::cast<cir::GlobalViewAttr>(catchAttrs[i]);
809 cir::EhTypeIdOp::create(builder, dispLoc, globalView.getSymbol());
810 auto cmpOp = cir::CmpOp::create(builder, dispLoc, cir::CmpOpKind::eq,
811 cmpTypeId, ehTypeIdOp.getTypeId());
813 cir::BrCondOp::create(builder, dispLoc, cmpOp, catchDests[i], falseDest,
814 mlir::ValueRange{cmpExnPtr, cmpTypeId},
815 mlir::ValueRange{cmpExnPtr, cmpTypeId});
818 falseDest = cmpBlock;
819 firstCmpBlock = cmpBlock;
822 firstCmpBlock = falseDest;
825 builder.setInsertionPoint(dispatch);
826 cir::BrOp::create(builder, dispLoc, firstCmpBlock,
827 mlir::ValueRange{exnPtr, typeId});
834mlir::FailureOr<cir::FuncOp>
835ItaniumEHLowering::resolveCatchCopyThunk(cir::ConstructCatchParamOp op) {
836 mlir::FlatSymbolRefAttr thunkRef = op.getCopyFnAttr();
837 mlir::StringAttr thunkName = thunkRef.getAttr();
838 auto cached = catchCopyThunks.find(thunkName);
839 if (cached != catchCopyThunks.end())
840 return cached->second;
842 cir::FuncOp thunk = mod.lookupSymbol<cir::FuncOp>(thunkRef);
844 return op.emitError(
"could not resolve catch-copy thunk symbol");
845 assert(thunk->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()) &&
846 "verifier should have rejected non-thunk catch-copy reference");
847 if (thunk.isDeclaration())
848 return op.emitError(
"catch-copy thunk has no body to inline");
850 mlir::Region &thunkRegion = thunk.getRegion();
851 if (!llvm::hasSingleElement(thunkRegion))
852 return op.emitError(
"multi-block catch-copy thunks are NYI");
854 mlir::Block &thunkEntry = thunkRegion.front();
855 assert(thunkEntry.getNumArguments() == 2 &&
856 "catch-copy thunk must have exactly two parameters");
857 if (!mlir::isa<cir::ReturnOp>(thunkEntry.getTerminator()))
858 return op.emitError(
"catch-copy thunk must end in cir.return");
860 catchCopyThunks[thunkName] = thunk;
868ItaniumEHLowering::lowerConstructCatchParam(cir::ConstructCatchParamOp op,
869 mlir::Value exnPtr) {
872 mlir::Location loc = op.getLoc();
873 mlir::Value paramAddr = op.getParamAddr();
874 cir::PointerType paramAddrType =
875 mlir::cast<cir::PointerType>(paramAddr.getType());
877 if (op.getKind() == cir::InitCatchKind::ReferenceToPointer) {
879 constexpr unsigned headerSize = 32;
881 builder.setInsertionPoint(op);
882 auto index = cir::ConstantOp::create(
883 builder, loc, cir::IntAttr::get(u32Type, headerSize));
884 assert((exnPtr.getType() == voidPtrType || exnPtr.getType() == u8PtrType) &&
885 "lowerConstructCatchParam exn ptr not void* or i8*");
887 cir::PtrStrideOp::create(builder, loc, exnPtr.getType(), exnPtr, index);
889 cir::CastOp::create(builder, loc, paramAddrType.getPointee(),
890 cir::CastKind::bitcast, exnObj);
891 cir::StoreOp::create(builder, loc, casted, paramAddr, {}, {}, {}, {}, {});
896 if (op.getKind() != cir::InitCatchKind::NonTrivialCopy)
897 return op.emitOpError(
"only reference_to_pointer and non_trivial_copy "
898 "kinds are supported");
900 ensureRuntimeDecls(loc);
901 ensureClangCallTerminate(loc);
904 builder.setInsertionPoint(op);
905 cir::CallOp getExnCall = cir::CallOp::create(
906 builder, loc, mlir::FlatSymbolRefAttr::get(getExceptionPtrFunc),
907 u8PtrType, mlir::ValueRange{exnPtr});
908 getExnCall.setNothrowAttr(builder.getUnitAttr());
909 mlir::Value adjusted =
910 cir::CastOp::create(builder, loc, paramAddrType, cir::CastKind::bitcast,
911 getExnCall.getResult());
914 mlir::FailureOr<cir::FuncOp> thunkOr = resolveCatchCopyThunk(op);
915 if (mlir::failed(thunkOr))
916 return mlir::failure();
917 cir::FuncOp thunk = *thunkOr;
921 assert(llvm::hasSingleElement(thunk.getRegion()) &&
922 "multi-block catch-copy thunks are NYI");
925 mlir::Block &thunkEntry = thunk.getRegion().front();
926 mlir::IRMapping mapping;
927 mapping.map(thunkEntry.getArgument(0), paramAddr);
928 mapping.map(thunkEntry.getArgument(1), adjusted);
929 llvm::SmallVector<cir::CallOp> throwingCalls;
930 for (mlir::Operation &thunkOp : thunkEntry.without_terminator()) {
931 mlir::Operation *cloned = builder.clone(thunkOp, mapping);
932 if (cir::CallOp callOp = mlir::dyn_cast<cir::CallOp>(cloned))
933 if (!callOp.getNothrow())
934 throwingCalls.push_back(callOp);
938 if (throwingCalls.empty())
939 return mlir::success();
943 mlir::IRRewriter rewriter(builder);
944 mlir::Block *terminateBlock =
nullptr;
945 for (cir::CallOp call : throwingCalls) {
947 terminateBlock = buildTerminateBlock(call->getParentOfType<cir::FuncOp>(),
951 return mlir::success();
958mlir::LogicalResult ItaniumEHLowering::lowerTryThrow(cir::TryThrowOp op) {
961 mlir::Location loc = op.getLoc();
962 mlir::Block *normalDest = op.getNormalDest();
963 mlir::Block *unwindDest = op.getUnwindDest();
964 builder.setInsertionPoint(op);
967 ensureCxaRethrowDecl(loc);
968 cir::TryCallOp::create(
969 builder, loc, mlir::FlatSymbolRefAttr::get(cxaRethrowFunc), voidType,
970 normalDest, unwindDest, mlir::ValueRange{});
972 return mlir::success();
975 ensureCxaThrowDecl(loc);
978 mlir::Value exnPtr = op.getExceptionPtr();
979 if (exnPtr.getType() != voidPtrType)
980 exnPtr = cir::CastOp::create(builder, loc, voidPtrType,
981 cir::CastKind::bitcast, exnPtr);
986 mlir::FlatSymbolRefAttr typeInfoAttr = op.getTypeInfoAttr();
987 auto typeInfoGlobal = mod.lookupSymbol<cir::GlobalOp>(typeInfoAttr);
989 return op.emitError(
"type_info symbol not found in module");
990 auto typeInfoPtrTy = cir::PointerType::get(typeInfoGlobal.getSymType());
991 mlir::Value typeInfo = cir::GetGlobalOp::create(builder, loc, typeInfoPtrTy,
992 typeInfoAttr.getValue());
993 if (typeInfo.getType() != voidPtrType)
994 typeInfo = cir::CastOp::create(builder, loc, voidPtrType,
995 cir::CastKind::bitcast, typeInfo);
999 if (mlir::FlatSymbolRefAttr dtorAttr = op.getDtorAttr()) {
1000 auto dtorFunc = mod.lookupSymbol<cir::FuncOp>(dtorAttr);
1002 return op.emitError(
"dtor symbol not found in module");
1003 auto dtorPtrTy = cir::PointerType::get(dtorFunc.getFunctionType());
1005 cir::GetGlobalOp::create(builder, loc, dtorPtrTy, dtorAttr.getValue());
1006 if (dtor.getType() != voidPtrType)
1007 dtor = cir::CastOp::create(builder, loc, voidPtrType,
1008 cir::CastKind::bitcast, dtor);
1010 dtor = cir::ConstantOp::create(
1012 cir::ConstPtrAttr::get(voidPtrType, builder.getI64IntegerAttr(0)));
1015 cir::TryCallOp::create(
1016 builder, loc, mlir::FlatSymbolRefAttr::get(cxaThrowFunc), voidType,
1017 normalDest, unwindDest, mlir::ValueRange{exnPtr, typeInfo, dtor});
1019 return mlir::success();
1047void ItaniumEHLowering::lowerInitCatchParam(cir::InitCatchParamOp op) {
1048 builder.setInsertionPoint(op);
1049 mlir::Location loc = op.getLoc();
1050 mlir::Value exnPtr = op.getExnPtr();
1051 mlir::Value paramAddr = op.getParamAddr();
1052 auto paramAddrType = mlir::cast<cir::PointerType>(paramAddr.getType());
1053 mlir::Type elementType = paramAddrType.getPointee();
1054 cir::InitCatchKind
kind = op.getKind();
1057 case InitCatchKind::Reference: {
1058 mlir::Value casted = cir::CastOp::create(builder, loc, elementType,
1059 cir::CastKind::bitcast, exnPtr);
1060 cir::StoreOp::create(builder, loc, casted, paramAddr, {}, {}, {}, {}, {});
1063 case InitCatchKind::ReferenceToPointer:
1067 case InitCatchKind::ReferenceToRecordPointer: {
1073 auto caughtType = mlir::cast<cir::PointerType>(
1074 mlir::cast<cir::PointerType>(elementType).getPointee());
1075 cir::AllocaOp byRefTmp;
1077 mlir::OpBuilder::InsertionGuard guard(builder);
1078 builder.setInsertionPointToStart(
1079 &op->getParentOfType<cir::FuncOp>().getBody().front());
1080 cir::CIRDataLayout dataLayout(mod);
1082 dataLayout.getAlignment(caughtType,
true).value();
1084 cir::AllocaOp::create(builder, loc, elementType,
"exn.byref.tmp",
1085 builder.getI64IntegerAttr(alignment));
1087 mlir::Value casted = cir::CastOp::create(builder, loc, caughtType,
1088 cir::CastKind::bitcast, exnPtr);
1089 cir::StoreOp::create(builder, loc, casted, byRefTmp, {}, {}, {}, {}, {});
1090 cir::StoreOp::create(builder, loc, byRefTmp, paramAddr, {}, {}, {}, {}, {});
1093 case InitCatchKind::TrivialCopy: {
1094 mlir::Value srcPtr = cir::CastOp::create(builder, loc, paramAddrType,
1095 cir::CastKind::bitcast, exnPtr);
1096 cir::CopyOp::create(builder, loc, paramAddr, srcPtr, {}, {});
1099 case InitCatchKind::NonTrivialCopy:
1103 case InitCatchKind::Scalar: {
1107 mlir::Value srcPtr = cir::CastOp::create(builder, loc, paramAddrType,
1108 cir::CastKind::bitcast, exnPtr);
1109 auto loadOp = cir::LoadOp::create(builder, loc, elementType, srcPtr);
1110 cir::StoreOp::create(builder, loc, loadOp.getResult(), paramAddr, {}, {},
1114 case InitCatchKind::Pointer: {
1115 mlir::Value casted = cir::CastOp::create(builder, loc, elementType,
1116 cir::CastKind::bitcast, exnPtr);
1117 cir::StoreOp::create(builder, loc, casted, paramAddr, {}, {}, {}, {}, {});
1120 case InitCatchKind::Objc:
1121 llvm_unreachable(
"InitCatchParam: ObjCLifetime is NYI");
1132struct CIREHABILoweringPass
1133 :
public impl::CIREHABILoweringBase<CIREHABILoweringPass> {
1134 CIREHABILoweringPass() =
default;
1135 void runOnOperation()
override;
1141static void eraseCatchCopyThunks(mlir::ModuleOp mod) {
1142 llvm::StringRef catchHelperAttr =
1143 cir::CIRDialect::getCatchCopyThunkAttrName();
1144 for (cir::FuncOp f : llvm::make_early_inc_range(mod.getOps<cir::FuncOp>())) {
1145 if (!f->hasAttr(catchHelperAttr))
1149 assert(mlir::SymbolTable::symbolKnownUseEmpty(f, mod) &&
1150 "catch-init helper has remaining users");
1155void CIREHABILoweringPass::runOnOperation() {
1156 auto mod = mlir::cast<mlir::ModuleOp>(getOperation());
1161 auto tripleAttr = mlir::dyn_cast_if_present<mlir::StringAttr>(
1162 mod->getAttr(cir::CIRDialect::getTripleAttrName()));
1164 mod.emitError(
"Module has no target triple");
1171 llvm::Triple triple(tripleAttr.getValue());
1172 std::unique_ptr<EHABILowering> lowering;
1173 if (triple.isWindowsMSVCEnvironment()) {
1175 "EH ABI lowering is not yet implemented for the Microsoft ABI");
1176 return signalPassFailure();
1178 lowering = std::make_unique<ItaniumEHLowering>(mod);
1181 if (mlir::failed(lowering->run()))
1182 return signalPassFailure();
1185 eraseCatchCopyThunks(mod);
1191 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)
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
static bool opFuncCallingConv()
static bool sizeOfUnwindException()