19#include "llvm/ADT/SmallPtrSet.h"
24#define GEN_PASS_DEF_CIRFORWARDRETURNSLOT
25#include "clang/CIR/Dialect/Passes.h.inc"
30struct CIRForwardReturnSlotPass
31 :
public impl::CIRForwardReturnSlotBase<CIRForwardReturnSlotPass> {
32 using CIRForwardReturnSlotBase::CIRForwardReturnSlotBase;
34 void runOnOperation()
override;
38static cir::StoreOp getStoreToSlot(Operation *op,
Value slot) {
39 auto store = dyn_cast_if_present<cir::StoreOp>(op);
43 if (!store || store.getAddr() != slot || store.isVolatileOrAtomic())
49static bool isUsedAfter(
Value value, Operation *op) {
50 Block *block = op->getBlock();
51 return llvm::any_of(value.getUsers(), [&](Operation *user) {
52 return user->getBlock() == block && op->isBeforeInBlock(user);
60static bool reachesThroughSinglePredecessors(cir::StoreOp store,
62 Block *storeBlock = store->getBlock();
63 if (load->getBlock() == storeBlock)
64 return store->isBeforeInBlock(load);
70 for (Block *block = load->getBlock(); block != storeBlock;
71 block = block->getSinglePredecessor()) {
72 if (!block || !visited.insert(block).second)
81static cir::ReturnOp getOnlyValueReturn(cir::FuncOp func) {
82 if (func.getFunctionType().hasVoidReturn())
85 WalkResult walk = func.walk([&](cir::ReturnOp op) {
87 return WalkResult::interrupt();
89 return WalkResult::advance();
91 if (walk.wasInterrupted())
99static cir::LoadOp getReturnSlotLoad(cir::ReturnOp ret) {
102 auto load = ret.getInput().front().getDefiningOp<cir::LoadOp>();
103 if (!load || !load->hasOneUse() || load->getBlock() != ret->getBlock() ||
104 load.isVolatileOrAtomic())
108 auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>();
109 if (!slot || !slot.getReturnSlot() ||
110 isa<cir::RecordType, cir::ArrayType, cir::ComplexType>(
111 slot.getAllocaType()))
119static cir::StoreOp findDominatingStoreToReturnSlot(cir::LoadOp load) {
120 Value slot = load.getAddr();
125 if (!slot.hasNUses(2)) {
126 if (isUsedAfter(slot, load))
132 return getStoreToSlot(load->getPrevNode(), slot);
135 Operation *user = *llvm::find_if(slot.getUsers(), [&](Operation *op) {
136 return op != load.getOperation();
138 cir::StoreOp store = getStoreToSlot(user, slot);
139 if (!store || !reachesThroughSinglePredecessors(store, load))
146static bool forwardReturnSlot(cir::FuncOp func) {
147 cir::ReturnOp ret = getOnlyValueReturn(func);
150 cir::LoadOp load = getReturnSlotLoad(ret);
153 cir::StoreOp store = findDominatingStoreToReturnSlot(load);
157 auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>();
158 ret.getInputMutable().assign(store.getValue());
161 if (slot->use_empty())
166void CIRForwardReturnSlotPass::runOnOperation() {
167 if (!forwardReturnSlot(getOperation()))
168 markAllAnalysesPreserved();
174 return std::make_unique<CIRForwardReturnSlotPass>();
std::unique_ptr< Pass > createCIRForwardReturnSlotPass()
static bool functionUsesSEHTry()
static bool emitLifetimeMarkers()
static bool fakeUseCleanup()