Debian Codegraph @

flang/lib/Optimizer/Transforms/StackReclaim.cpp

raw
1 //===- StackReclaim.cpp -- Insert stacksave/stackrestore in region --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "flang/Common/Fortran.h"
10 #include "flang/Optimizer/Dialect/FIRDialect.h"
11 #include "flang/Optimizer/Dialect/FIROps.h"
12 #include "flang/Optimizer/Transforms/Passes.h"
13 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
14 #include "mlir/IR/Matchers.h"
15 #include "mlir/Pass/Pass.h"
16
17 namespace fir {
18 #define GEN_PASS_DEF_STACKRECLAIM
19 #include "flang/Optimizer/Transforms/Passes.h.inc"
20 } // namespace fir
21
22 using namespace mlir;
23
24 namespace {
25
26 class StackReclaimPass : public fir::impl::StackReclaimBase<StackReclaimPass> {
27 public:
28 using StackReclaimBase<StackReclaimPass>::StackReclaimBase;
29
30 void runOnOperation() override;
31 };
32 } // namespace
33
34 uint64_t getAllocaAddressSpace(Operation *op) {
35 mlir::ModuleOp module = mlir::dyn_cast_or_null<mlir::ModuleOp>(op);
36 if (!module)
37 module = op->getParentOfType<mlir::ModuleOp>();
38
39 if (mlir::Attribute addrSpace =
40 mlir::DataLayout(module).getAllocaMemorySpace())
41 return llvm::cast<mlir::IntegerAttr>(addrSpace).getUInt();
42 return 0;
43 }
44
45 void StackReclaimPass::runOnOperation() {
46 auto *op = getOperation();
47 auto *context = &getContext();
48 mlir::OpBuilder builder(context);
49 mlir::Type voidPtr =
50 mlir::LLVM::LLVMPointerType::get(context, getAllocaAddressSpace(op));
51
52 op->walk([&](fir::DoLoopOp loopOp) {
53 mlir::Location loc = loopOp.getLoc();
54
55 if (!loopOp.getRegion().getOps<fir::AllocaOp>().empty()) {
56 builder.setInsertionPointToStart(&loopOp.getRegion().front());
57 auto stackSaveOp = builder.create<LLVM::StackSaveOp>(loc, voidPtr);
58
59 auto *terminator = loopOp.getRegion().back().getTerminator();
60 builder.setInsertionPoint(terminator);
61 builder.create<LLVM::StackRestoreOp>(loc, stackSaveOp);
62 }
63 });
64 }