30#include "mlir/IR/Builders.h"
31#include "mlir/IR/IRMapping.h"
32#include "mlir/IR/PatternMatch.h"
39#include "llvm/ADT/DenseMap.h"
40#include "llvm/ADT/SetVector.h"
41#include "llvm/ADT/SmallVector.h"
42#include "llvm/TargetParser/Triple.h"
48#define GEN_PASS_DEF_CIREHABILOWERING
49#include "clang/CIR/Dialect/Passes.h.inc"
60static cir::FuncOp getOrCreateRuntimeFuncDecl(mlir::ModuleOp mod,
63 cir::FuncType funcTy) {
64 if (
auto existing = mod.lookupSymbol<cir::FuncOp>(
name))
67 mlir::OpBuilder builder(mod.getContext());
68 builder.setInsertionPointToEnd(mod.getBody());
69 auto funcOp = cir::FuncOp::create(builder, loc,
name, funcTy);
70 funcOp.setLinkage(cir::GlobalLinkageKind::ExternalLinkage);
83 explicit EHABILowering(mlir::ModuleOp mod)
84 : mod(mod), ctx(mod.getContext()), builder(ctx) {}
85 virtual ~EHABILowering() =
default;
88 virtual mlir::LogicalResult
run() = 0;
92 mlir::MLIRContext *ctx;
93 mlir::OpBuilder builder;
107class ItaniumEHLowering :
public EHABILowering {
109 using EHABILowering::EHABILowering;
110 mlir::LogicalResult
run()
override;
115 using EhTokenMap = DenseMap<mlir::Value, std::pair<mlir::Value, mlir::Value>>;
117 cir::VoidType voidType;
118 cir::PointerType voidPtrType;
119 cir::PointerType u8PtrType;
120 cir::IntType u32Type;
124 cir::FuncOp personalityFunc;
125 cir::FuncOp beginCatchFunc;
126 cir::FuncOp endCatchFunc;
127 cir::FuncOp getExceptionPtrFunc;
128 cir::FuncOp clangCallTerminateFunc;
129 cir::FuncOp cxaThrowFunc;
130 cir::FuncOp cxaRethrowFunc;
132 DenseMap<mlir::StringAttr, cir::FuncOp> catchCopyThunks;
134 constexpr const static ::llvm::StringLiteral kGxxPersonality =
135 "__gxx_personality_v0";
137 void ensureRuntimeDecls(mlir::Location loc);
138 void ensureClangCallTerminate(mlir::Location loc);
139 void ensureCxaThrowDecl(mlir::Location loc);
140 void ensureCxaRethrowDecl(mlir::Location loc);
141 mlir::Block *buildTerminateBlock(cir::FuncOp funcOp, mlir::Location loc);
142 mlir::FailureOr<cir::FuncOp>
143 resolveCatchCopyThunk(cir::ConstructCatchParamOp op);
144 mlir::LogicalResult lowerFunc(cir::FuncOp funcOp);
146 lowerEhInitiate(cir::EhInitiateOp initiateOp,
147 llvm::ArrayRef<cir::EhDispatchOp> reachedDispatches,
148 bool reachesCleanup, EhTokenMap &ehTokenMap);
149 void lowerDispatch(cir::EhDispatchOp dispatch, mlir::Value exnPtr,
151 mlir::LogicalResult lowerConstructCatchParam(cir::ConstructCatchParamOp op,
153 void lowerInitCatchParam(cir::InitCatchParamOp op);
154 mlir::LogicalResult lowerTryThrow(cir::TryThrowOp op);
158mlir::LogicalResult ItaniumEHLowering::run() {
161 voidType = cir::VoidType::get(ctx);
162 voidPtrType = cir::PointerType::get(voidType);
163 auto u8Type = cir::IntType::get(ctx, 8,
false);
164 u8PtrType = cir::PointerType::get(u8Type);
165 u32Type = cir::IntType::get(ctx, 32,
false);
167 for (cir::FuncOp funcOp : mod.getOps<cir::FuncOp>()) {
168 if (mlir::failed(lowerFunc(funcOp)))
169 return mlir::failure();
171 return mlir::success();
176void ItaniumEHLowering::ensureRuntimeDecls(mlir::Location loc) {
179 if (!personalityFunc) {
180 auto s32Type = cir::IntType::get(ctx, 32,
true);
181 auto personalityFuncTy = cir::FuncType::get({}, s32Type,
true);
182 personalityFunc = getOrCreateRuntimeFuncDecl(mod, loc, kGxxPersonality,
186 if (!beginCatchFunc) {
187 auto beginCatchFuncTy =
188 cir::FuncType::get({voidPtrType}, u8PtrType,
false);
189 beginCatchFunc = getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_begin_catch",
194 auto endCatchFuncTy = cir::FuncType::get({}, voidType,
false);
196 getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_end_catch", endCatchFuncTy);
199 if (!getExceptionPtrFunc) {
200 auto getExceptionPtrFuncTy =
201 cir::FuncType::get({voidPtrType}, u8PtrType,
false);
202 getExceptionPtrFunc = getOrCreateRuntimeFuncDecl(
203 mod, loc,
"__cxa_get_exception_ptr", getExceptionPtrFuncTy);
216void ItaniumEHLowering::ensureClangCallTerminate(mlir::Location loc) {
217 if (clangCallTerminateFunc)
220 ensureRuntimeDecls(loc);
222 if (
auto existing = mod.lookupSymbol<cir::FuncOp>(
"__clang_call_terminate")) {
223 clangCallTerminateFunc = existing;
227 auto funcTy = cir::FuncType::get({voidPtrType}, voidType,
false);
228 builder.setInsertionPointToEnd(mod.getBody());
230 cir::FuncOp::create(builder, loc,
"__clang_call_terminate", funcTy);
231 funcOp.setLinkage(cir::GlobalLinkageKind::LinkOnceODRLinkage);
232 funcOp.setGlobalVisibility(cir::VisibilityKind::Hidden);
234 mlir::Block *entryBlock = funcOp.addEntryBlock();
235 builder.setInsertionPointToStart(entryBlock);
236 mlir::Value exnArg = entryBlock->getArgument(0);
238 auto catchCall = cir::CallOp::create(
239 builder, loc, mlir::FlatSymbolRefAttr::get(beginCatchFunc), u8PtrType,
240 mlir::ValueRange{exnArg});
241 catchCall.setNothrowAttr(builder.getUnitAttr());
243 auto terminateFuncDecl = getOrCreateRuntimeFuncDecl(
244 mod, loc,
"_ZSt9terminatev",
245 cir::FuncType::get({}, voidType,
false));
246 terminateFuncDecl->setAttr(cir::CIRDialect::getNoReturnAttrName(),
247 builder.getUnitAttr());
248 auto terminateCall = cir::CallOp::create(
249 builder, loc, mlir::FlatSymbolRefAttr::get(terminateFuncDecl), voidType,
251 terminateCall.setNothrowAttr(builder.getUnitAttr());
252 terminateCall->setAttr(cir::CIRDialect::getNoReturnAttrName(),
253 builder.getUnitAttr());
255 cir::UnreachableOp::create(builder, loc);
257 funcOp->setAttr(cir::CIRDialect::getNoReturnAttrName(),
258 builder.getUnitAttr());
259 clangCallTerminateFunc = funcOp;
265void ItaniumEHLowering::ensureCxaThrowDecl(mlir::Location loc) {
268 auto throwFuncTy = cir::FuncType::get({voidPtrType, voidPtrType, voidPtrType},
271 getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_throw", throwFuncTy);
277void ItaniumEHLowering::ensureCxaRethrowDecl(mlir::Location loc) {
280 auto rethrowFuncTy = cir::FuncType::get({}, voidType,
false);
282 getOrCreateRuntimeFuncDecl(mod, loc,
"__cxa_rethrow", rethrowFuncTy);
286mlir::Block *ItaniumEHLowering::buildTerminateBlock(cir::FuncOp funcOp,
287 mlir::Location loc) {
288 assert(clangCallTerminateFunc &&
289 "ensureClangCallTerminate must run before buildTerminateBlock");
290 mlir::Region &body = funcOp.getRegion();
291 mlir::Block *terminateBlock = builder.createBlock(&body, body.end());
292 auto inflight = cir::EhInflightOp::create(
293 builder, loc,
false,
true,
295 auto terminateCall = cir::CallOp::create(
296 builder, loc, mlir::FlatSymbolRefAttr::get(clangCallTerminateFunc),
297 voidType, mlir::ValueRange{inflight.getExceptionPtr()});
298 terminateCall.setNothrowAttr(builder.getUnitAttr());
299 terminateCall->setAttr(cir::CIRDialect::getNoReturnAttrName(),
300 builder.getUnitAttr());
301 cir::UnreachableOp::create(builder, loc);
302 return terminateBlock;
318static void collectReachableDispatches(
319 mlir::Value rootToken,
320 llvm::SmallSetVector<cir::EhDispatchOp, 4> &dispatches,
321 bool &reachesCleanup) {
322 llvm::SmallVector<mlir::Value> worklist;
323 llvm::SmallPtrSet<mlir::Value, 8> visited;
324 worklist.push_back(rootToken);
328 for (
unsigned i = 0; i < worklist.size(); ++i) {
329 mlir::Value current = worklist[i];
330 if (!visited.insert(current).second)
332 for (mlir::OpOperand &use : current.getUses()) {
333 mlir::Operation *user = use.getOwner();
338 if (mlir::isa<cir::BeginCleanupOp>(user))
339 reachesCleanup =
true;
340 if (
auto dispatch = mlir::dyn_cast<cir::EhDispatchOp>(user))
341 dispatches.insert(dispatch);
343 for (
unsigned s = 0, e = user->getNumSuccessors(); s < e; ++s)
344 for (mlir::BlockArgument arg : user->getSuccessor(s)->getArguments())
345 if (mlir::isa<cir::EhTokenType>(
arg.getType()))
346 worklist.push_back(arg);
352mlir::LogicalResult ItaniumEHLowering::lowerFunc(cir::FuncOp funcOp) {
353 if (funcOp.isDeclaration())
354 return mlir::success();
360 SmallVector<cir::EhInitiateOp> initiateOps;
361 funcOp.walk([&](cir::EhInitiateOp op) { initiateOps.push_back(op); });
362 if (initiateOps.empty())
363 return mlir::success();
365 ensureRuntimeDecls(funcOp.getLoc());
372 if (!funcOp.getPersonality())
373 funcOp.setPersonality(kGxxPersonality);
387 struct InitiateEHInfo {
388 llvm::SmallSetVector<cir::EhDispatchOp, 4> reachedDispatches;
389 bool reachesCleanup =
false;
391 llvm::DenseMap<mlir::Operation *, InitiateEHInfo> initiateInfo;
392 llvm::SmallSetVector<cir::EhDispatchOp, 4> dispatchesToLower;
393 for (cir::EhInitiateOp initiateOp : initiateOps) {
394 InitiateEHInfo &info = initiateInfo[initiateOp.getOperation()];
395 collectReachableDispatches(initiateOp.getEhToken(), info.reachedDispatches,
396 info.reachesCleanup);
397 dispatchesToLower.insert(info.reachedDispatches.begin(),
398 info.reachedDispatches.end());
401 EhTokenMap ehTokenMap;
402 for (cir::EhInitiateOp initiateOp : initiateOps) {
403 const InitiateEHInfo &info = initiateInfo[initiateOp.getOperation()];
404 if (mlir::failed(lowerEhInitiate(initiateOp,
405 info.reachedDispatches.getArrayRef(),
406 info.reachesCleanup, ehTokenMap)))
407 return mlir::failure();
414 for (cir::EhDispatchOp dispatch : dispatchesToLower) {
415 auto [exnPtr, typeId] = ehTokenMap.lookup(dispatch.getEhToken());
416 assert(exnPtr && typeId &&
417 "dispatch eh_token must be registered in ehTokenMap");
418 lowerDispatch(dispatch, exnPtr, typeId);
423 for (mlir::Block &block : funcOp.getBody()) {
424 for (
int i = block.getNumArguments() - 1; i >= 0; --i) {
425 if (mlir::isa<cir::EhTokenType>(block.getArgument(i).getType()))
426 block.eraseArgument(i);
433 SmallVector<cir::InitCatchParamOp> initCatchOps;
434 funcOp.walk([&](cir::InitCatchParamOp op) { initCatchOps.push_back(op); });
435 for (cir::InitCatchParamOp op : initCatchOps)
436 lowerInitCatchParam(op);
441 SmallVector<cir::TryThrowOp> tryThrowOps;
442 funcOp.walk([&](cir::TryThrowOp op) { tryThrowOps.push_back(op); });
443 for (cir::TryThrowOp op : tryThrowOps)
444 if (mlir::failed(lowerTryThrow(op)))
445 return mlir::failure();
447 return mlir::success();
476mlir::LogicalResult ItaniumEHLowering::lowerEhInitiate(
477 cir::EhInitiateOp initiateOp,
478 llvm::ArrayRef<cir::EhDispatchOp> reachedDispatches,
bool reachesCleanup,
479 EhTokenMap &ehTokenMap) {
480 mlir::Value rootToken = initiateOp.getEhToken();
490 mlir::ArrayAttr catchTypeList;
491 bool catchAll =
false;
492 SmallVector<mlir::Attribute> typeSymbols;
493 for (cir::EhDispatchOp dispatch : reachedDispatches) {
494 if (mlir::ArrayAttr catchTypes = dispatch.getCatchTypesAttr())
495 for (mlir::Attribute attr : catchTypes)
496 typeSymbols.push_back(
497 mlir::cast<cir::GlobalViewAttr>(attr).getSymbol());
498 if (dispatch.getDefaultIsCatchAll()) {
503 assert(dispatch == reachedDispatches.back() &&
504 "catch-all must be the last reachable dispatch");
508 if (!typeSymbols.empty())
509 catchTypeList = builder.getArrayAttr(typeSymbols);
511 builder.setInsertionPoint(initiateOp);
512 auto inflightOp = cir::EhInflightOp::create(
513 builder, initiateOp.getLoc(),
514 initiateOp.getCleanup() || reachesCleanup,
515 catchAll, catchTypeList);
517 ehTokenMap[rootToken] = {inflightOp.getExceptionPtr(),
518 inflightOp.getTypeId()};
524 SmallVector<mlir::Value> worklist;
525 SmallPtrSet<mlir::Value, 8> visited;
526 worklist.push_back(rootToken);
528 while (!worklist.empty()) {
529 mlir::Value current = worklist.pop_back_val();
530 if (!visited.insert(current).second)
535 SmallVector<mlir::Operation *> users;
536 for (mlir::OpOperand &use : current.getUses())
537 users.push_back(use.getOwner());
541 for (mlir::Operation *user : users) {
547 for (
unsigned s = 0; s < user->getNumSuccessors(); ++s) {
548 mlir::Block *succ = user->getSuccessor(s);
549 for (mlir::BlockArgument arg : succ->getArguments()) {
550 if (!mlir::isa<cir::EhTokenType>(
arg.getType()))
552 if (!ehTokenMap.count(arg)) {
553 mlir::Value ptrArg = succ->addArgument(voidPtrType,
arg.getLoc());
554 mlir::Value u32Arg = succ->addArgument(u32Type,
arg.getLoc());
555 ehTokenMap[
arg] = {ptrArg, u32Arg};
557 worklist.push_back(arg);
561 if (
auto op = mlir::dyn_cast<cir::BeginCleanupOp>(user)) {
564 for (
auto &tokenUsers :
565 llvm::make_early_inc_range(op.getCleanupToken().getUses())) {
567 mlir::dyn_cast<cir::EndCleanupOp>(tokenUsers.getOwner()))
571 }
else if (
auto op = mlir::dyn_cast<cir::BeginCatchOp>(user)) {
574 for (
auto &tokenUsers :
575 llvm::make_early_inc_range(op.getCatchToken().getUses())) {
577 mlir::dyn_cast<cir::EndCatchOp>(tokenUsers.getOwner())) {
578 builder.setInsertionPoint(endOp);
579 cir::CallOp::create(builder, endOp.getLoc(),
580 mlir::FlatSymbolRefAttr::get(endCatchFunc),
581 voidType, mlir::ValueRange{});
586 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
587 builder.setInsertionPoint(op);
588 auto callOp = cir::CallOp::create(
589 builder, op.getLoc(), mlir::FlatSymbolRefAttr::get(beginCatchFunc),
590 u8PtrType, mlir::ValueRange{exnPtr});
591 mlir::Value castResult = callOp.getResult();
592 mlir::Type expectedPtrType = op.getExnPtr().getType();
593 if (castResult.getType() != expectedPtrType)
595 cir::CastOp::create(builder, op.getLoc(), expectedPtrType,
596 cir::CastKind::bitcast, callOp.getResult());
597 op.getExnPtr().replaceAllUsesWith(castResult);
599 }
else if (
auto op = mlir::dyn_cast<cir::ConstructCatchParamOp>(user)) {
600 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
601 if (mlir::failed(lowerConstructCatchParam(op, exnPtr)))
602 return mlir::failure();
603 }
else if (mlir::isa<cir::EhDispatchOp>(user)) {
609 }
else if (
auto op = mlir::dyn_cast<cir::EhTerminateOp>(user)) {
610 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
611 ensureClangCallTerminate(op.getLoc());
612 builder.setInsertionPoint(op);
613 auto call = cir::CallOp::create(
614 builder, op.getLoc(),
615 mlir::FlatSymbolRefAttr::get(clangCallTerminateFunc), voidType,
616 mlir::ValueRange{exnPtr});
617 call.setNothrowAttr(builder.getUnitAttr());
618 call->setAttr(cir::CIRDialect::getNoReturnAttrName(),
619 builder.getUnitAttr());
620 cir::UnreachableOp::create(builder, op.getLoc());
622 }
else if (
auto op = mlir::dyn_cast<cir::ResumeOp>(user)) {
623 auto [exnPtr, typeId] = ehTokenMap.lookup(op.getEhToken());
624 builder.setInsertionPoint(op);
625 cir::ResumeFlatOp::create(builder, op.getLoc(), exnPtr, typeId);
627 }
else if (
auto op = mlir::dyn_cast<cir::BrOp>(user)) {
629 SmallVector<mlir::Value> newOperands;
630 bool changed =
false;
631 for (mlir::Value operand : op.getDestOperands()) {
632 auto it = ehTokenMap.find(operand);
633 if (it != ehTokenMap.end()) {
634 newOperands.push_back(it->second.first);
635 newOperands.push_back(it->second.second);
638 newOperands.push_back(operand);
642 builder.setInsertionPoint(op);
643 cir::BrOp::create(builder, op.getLoc(), op.getDest(), newOperands);
651 return mlir::success();
657void ItaniumEHLowering::lowerDispatch(cir::EhDispatchOp dispatch,
658 mlir::Value exnPtr, mlir::Value typeId) {
659 mlir::Location dispLoc = dispatch.getLoc();
660 mlir::Block *defaultDest = dispatch.getDefaultDestination();
661 mlir::ArrayAttr catchTypes = dispatch.getCatchTypesAttr();
662 mlir::SuccessorRange catchDests = dispatch.getCatchDestinations();
663 mlir::Block *dispatchBlock = dispatch->getBlock();
668 if (!catchTypes || catchTypes.empty()) {
670 builder.setInsertionPoint(dispatch);
671 cir::BrOp::create(builder, dispLoc, defaultDest,
672 mlir::ValueRange{exnPtr, typeId});
674 unsigned numCatches = catchTypes.size();
680 mlir::Block *
insertBefore = dispatchBlock->getNextNode();
681 mlir::Block *falseDest = defaultDest;
682 mlir::Block *firstCmpBlock =
nullptr;
683 for (
int i = numCatches - 1; i >= 0; --i) {
684 auto *cmpBlock = builder.createBlock(insertBefore, {voidPtrType, u32Type},
687 mlir::Value cmpExnPtr = cmpBlock->getArgument(0);
688 mlir::Value cmpTypeId = cmpBlock->getArgument(1);
690 auto globalView = mlir::cast<cir::GlobalViewAttr>(catchTypes[i]);
692 cir::EhTypeIdOp::create(builder, dispLoc, globalView.getSymbol());
693 auto cmpOp = cir::CmpOp::create(builder, dispLoc, cir::CmpOpKind::eq,
694 cmpTypeId, ehTypeIdOp.getTypeId());
696 cir::BrCondOp::create(builder, dispLoc, cmpOp, catchDests[i], falseDest,
697 mlir::ValueRange{cmpExnPtr, cmpTypeId},
698 mlir::ValueRange{cmpExnPtr, cmpTypeId});
701 falseDest = cmpBlock;
702 firstCmpBlock = cmpBlock;
706 builder.setInsertionPoint(dispatch);
707 cir::BrOp::create(builder, dispLoc, firstCmpBlock,
708 mlir::ValueRange{exnPtr, typeId});
716mlir::FailureOr<cir::FuncOp>
717ItaniumEHLowering::resolveCatchCopyThunk(cir::ConstructCatchParamOp op) {
718 mlir::FlatSymbolRefAttr thunkRef = op.getCopyFnAttr();
719 mlir::StringAttr thunkName = thunkRef.getAttr();
720 auto cached = catchCopyThunks.find(thunkName);
721 if (cached != catchCopyThunks.end())
722 return cached->second;
724 cir::FuncOp thunk = mod.lookupSymbol<cir::FuncOp>(thunkRef);
726 return op.emitError(
"could not resolve catch-copy thunk symbol");
727 assert(thunk->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()) &&
728 "verifier should have rejected non-thunk catch-copy reference");
729 if (thunk.isDeclaration())
730 return op.emitError(
"catch-copy thunk has no body to inline");
732 mlir::Region &thunkRegion = thunk.getRegion();
733 if (!llvm::hasSingleElement(thunkRegion))
734 return op.emitError(
"multi-block catch-copy thunks are NYI");
736 mlir::Block &thunkEntry = thunkRegion.front();
737 assert(thunkEntry.getNumArguments() == 2 &&
738 "catch-copy thunk must have exactly two parameters");
739 if (!mlir::isa<cir::ReturnOp>(thunkEntry.getTerminator()))
740 return op.emitError(
"catch-copy thunk must end in cir.return");
742 catchCopyThunks[thunkName] = thunk;
750ItaniumEHLowering::lowerConstructCatchParam(cir::ConstructCatchParamOp op,
751 mlir::Value exnPtr) {
752 mlir::Location loc = op.getLoc();
753 mlir::Value paramAddr = op.getParamAddr();
754 cir::PointerType paramAddrType =
755 mlir::cast<cir::PointerType>(paramAddr.getType());
757 if (op.getKind() == cir::InitCatchKind::Reference) {
759 constexpr unsigned headerSize = 32;
761 builder.setInsertionPoint(op);
762 auto index = cir::ConstantOp::create(
763 builder, loc, cir::IntAttr::get(u32Type, headerSize));
764 assert((exnPtr.getType() == voidPtrType || exnPtr.getType() == u8PtrType) &&
765 "lowerConstructCatchParam exn ptr not void* or i8*");
767 cir::PtrStrideOp::create(builder, loc, exnPtr.getType(), exnPtr, index);
769 cir::CastOp::create(builder, loc, paramAddrType.getPointee(),
770 cir::CastKind::bitcast, exnObj);
771 cir::StoreOp::create(builder, loc, casted, paramAddr, {}, {}, {}, {}, {});
776 if (op.getKind() != cir::InitCatchKind::NonTrivialCopy)
778 "ConstructCatchParam: only non_trivial_copy is supported");
780 ensureRuntimeDecls(loc);
781 ensureClangCallTerminate(loc);
784 builder.setInsertionPoint(op);
785 cir::CallOp getExnCall = cir::CallOp::create(
786 builder, loc, mlir::FlatSymbolRefAttr::get(getExceptionPtrFunc),
787 u8PtrType, mlir::ValueRange{exnPtr});
788 getExnCall.setNothrowAttr(builder.getUnitAttr());
789 mlir::Value adjusted =
790 cir::CastOp::create(builder, loc, paramAddrType, cir::CastKind::bitcast,
791 getExnCall.getResult());
794 mlir::FailureOr<cir::FuncOp> thunkOr = resolveCatchCopyThunk(op);
795 if (mlir::failed(thunkOr))
796 return mlir::failure();
797 cir::FuncOp thunk = *thunkOr;
801 assert(llvm::hasSingleElement(thunk.getRegion()) &&
802 "multi-block catch-copy thunks are NYI");
805 mlir::Block &thunkEntry = thunk.getRegion().front();
806 mlir::IRMapping mapping;
807 mapping.map(thunkEntry.getArgument(0), paramAddr);
808 mapping.map(thunkEntry.getArgument(1), adjusted);
809 llvm::SmallVector<cir::CallOp> throwingCalls;
810 for (mlir::Operation &thunkOp : thunkEntry.without_terminator()) {
811 mlir::Operation *cloned = builder.clone(thunkOp, mapping);
812 if (cir::CallOp callOp = mlir::dyn_cast<cir::CallOp>(cloned))
813 if (!callOp.getNothrow())
814 throwingCalls.push_back(callOp);
818 if (throwingCalls.empty())
819 return mlir::success();
823 mlir::IRRewriter rewriter(builder);
824 mlir::Block *terminateBlock =
nullptr;
825 for (cir::CallOp call : throwingCalls) {
827 terminateBlock = buildTerminateBlock(call->getParentOfType<cir::FuncOp>(),
831 return mlir::success();
838mlir::LogicalResult ItaniumEHLowering::lowerTryThrow(cir::TryThrowOp op) {
839 mlir::Location loc = op.getLoc();
840 mlir::Block *normalDest = op.getNormalDest();
841 mlir::Block *unwindDest = op.getUnwindDest();
842 builder.setInsertionPoint(op);
845 ensureCxaRethrowDecl(loc);
846 cir::TryCallOp::create(
847 builder, loc, mlir::FlatSymbolRefAttr::get(cxaRethrowFunc), voidType,
848 normalDest, unwindDest, mlir::ValueRange{});
850 return mlir::success();
853 ensureCxaThrowDecl(loc);
856 mlir::Value exnPtr = op.getExceptionPtr();
857 if (exnPtr.getType() != voidPtrType)
858 exnPtr = cir::CastOp::create(builder, loc, voidPtrType,
859 cir::CastKind::bitcast, exnPtr);
864 mlir::FlatSymbolRefAttr typeInfoAttr = op.getTypeInfoAttr();
865 auto typeInfoGlobal = mod.lookupSymbol<cir::GlobalOp>(typeInfoAttr);
867 return op.emitError(
"type_info symbol not found in module");
868 auto typeInfoPtrTy = cir::PointerType::get(typeInfoGlobal.getSymType());
869 mlir::Value typeInfo = cir::GetGlobalOp::create(builder, loc, typeInfoPtrTy,
870 typeInfoAttr.getValue());
871 if (typeInfo.getType() != voidPtrType)
872 typeInfo = cir::CastOp::create(builder, loc, voidPtrType,
873 cir::CastKind::bitcast, typeInfo);
877 if (mlir::FlatSymbolRefAttr dtorAttr = op.getDtorAttr()) {
878 auto dtorFunc = mod.lookupSymbol<cir::FuncOp>(dtorAttr);
880 return op.emitError(
"dtor symbol not found in module");
881 auto dtorPtrTy = cir::PointerType::get(dtorFunc.getFunctionType());
883 cir::GetGlobalOp::create(builder, loc, dtorPtrTy, dtorAttr.getValue());
884 if (dtor.getType() != voidPtrType)
885 dtor = cir::CastOp::create(builder, loc, voidPtrType,
886 cir::CastKind::bitcast, dtor);
888 dtor = cir::ConstantOp::create(
890 cir::ConstPtrAttr::get(voidPtrType, builder.getI64IntegerAttr(0)));
893 cir::TryCallOp::create(
894 builder, loc, mlir::FlatSymbolRefAttr::get(cxaThrowFunc), voidType,
895 normalDest, unwindDest, mlir::ValueRange{exnPtr, typeInfo, dtor});
897 return mlir::success();
920void ItaniumEHLowering::lowerInitCatchParam(cir::InitCatchParamOp op) {
921 builder.setInsertionPoint(op);
922 mlir::Location loc = op.getLoc();
923 mlir::Value exnPtr = op.getExnPtr();
924 mlir::Value paramAddr = op.getParamAddr();
925 auto paramAddrType = mlir::cast<cir::PointerType>(paramAddr.getType());
926 mlir::Type elementType = paramAddrType.getPointee();
927 cir::InitCatchKind
kind = op.getKind();
930 case InitCatchKind::Reference: {
934 if (
const auto ref = mlir::dyn_cast<cir::PointerType>(elementType)) {
937 if (
auto ptr = mlir::dyn_cast<cir::PointerType>(ref.getPointee()))
938 if (!mlir::isa<cir::RecordType>(ptr.getPointee()))
944 mlir::Value casted = cir::CastOp::create(builder, loc, elementType,
945 cir::CastKind::bitcast, exnPtr);
946 cir::StoreOp::create(builder, loc, casted, paramAddr, {}, {}, {}, {}, {});
949 case InitCatchKind::TrivialCopy: {
950 mlir::Value srcPtr = cir::CastOp::create(builder, loc, paramAddrType,
951 cir::CastKind::bitcast, exnPtr);
952 cir::CopyOp::create(builder, loc, paramAddr, srcPtr, {}, {});
955 case InitCatchKind::NonTrivialCopy:
959 case InitCatchKind::Scalar: {
963 mlir::Value srcPtr = cir::CastOp::create(builder, loc, paramAddrType,
964 cir::CastKind::bitcast, exnPtr);
965 auto loadOp = cir::LoadOp::create(builder, loc, elementType, srcPtr);
966 cir::StoreOp::create(builder, loc, loadOp.getResult(), paramAddr, {}, {},
970 case InitCatchKind::Pointer: {
971 mlir::Value casted = cir::CastOp::create(builder, loc, elementType,
972 cir::CastKind::bitcast, exnPtr);
973 cir::StoreOp::create(builder, loc, casted, paramAddr, {}, {}, {}, {}, {});
976 case InitCatchKind::Objc:
977 llvm_unreachable(
"InitCatchParam: ObjCLifetime is NYI");
988struct CIREHABILoweringPass
989 :
public impl::CIREHABILoweringBase<CIREHABILoweringPass> {
990 CIREHABILoweringPass() =
default;
991 void runOnOperation()
override;
997static void eraseCatchCopyThunks(mlir::ModuleOp mod) {
998 llvm::StringRef catchHelperAttr =
999 cir::CIRDialect::getCatchCopyThunkAttrName();
1000 for (cir::FuncOp f : llvm::make_early_inc_range(mod.getOps<cir::FuncOp>())) {
1001 if (!f->hasAttr(catchHelperAttr))
1005 assert(mlir::SymbolTable::symbolKnownUseEmpty(f, mod) &&
1006 "catch-init helper has remaining users");
1011void CIREHABILoweringPass::runOnOperation() {
1012 auto mod = mlir::cast<mlir::ModuleOp>(getOperation());
1017 auto tripleAttr = mlir::dyn_cast_if_present<mlir::StringAttr>(
1018 mod->getAttr(cir::CIRDialect::getTripleAttrName()));
1020 mod.emitError(
"Module has no target triple");
1027 llvm::Triple triple(tripleAttr.getValue());
1028 std::unique_ptr<EHABILowering> lowering;
1029 if (triple.isWindowsMSVCEnvironment()) {
1031 "EH ABI lowering is not yet implemented for the Microsoft ABI");
1032 return signalPassFailure();
1034 lowering = std::make_unique<ItaniumEHLowering>(mod);
1037 if (mlir::failed(lowering->run()))
1038 return signalPassFailure();
1041 eraseCatchCopyThunks(mod);
1047 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.
std::unique_ptr< Pass > createCIREHABILoweringPass()
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
static bool sizeOfUnwindException()