xref: /llvm-project/flang/lib/Optimizer/Builder/DoLoopHelper.cpp (revision 092601d4baab7c13c06b31eda2d5bed91d9a6b65)
1 //===-- DoLoopHelper.cpp --------------------------------------------------===//
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/Optimizer/Builder/DoLoopHelper.h"
10 
11 //===----------------------------------------------------------------------===//
12 // DoLoopHelper implementation
13 //===----------------------------------------------------------------------===//
14 
15 fir::DoLoopOp
createLoop(mlir::Value lb,mlir::Value ub,mlir::Value step,const BodyGenerator & bodyGenerator)16 fir::factory::DoLoopHelper::createLoop(mlir::Value lb, mlir::Value ub,
17                                        mlir::Value step,
18                                        const BodyGenerator &bodyGenerator) {
19   auto lbi = builder.convertToIndexType(loc, lb);
20   auto ubi = builder.convertToIndexType(loc, ub);
21   assert(step && "step must be an actual Value");
22   auto inc = builder.convertToIndexType(loc, step);
23   auto loop = builder.create<fir::DoLoopOp>(loc, lbi, ubi, inc);
24   auto insertPt = builder.saveInsertionPoint();
25   builder.setInsertionPointToStart(loop.getBody());
26   auto index = loop.getInductionVar();
27   bodyGenerator(builder, index);
28   builder.restoreInsertionPoint(insertPt);
29   return loop;
30 }
31 
32 fir::DoLoopOp
createLoop(mlir::Value lb,mlir::Value ub,const BodyGenerator & bodyGenerator)33 fir::factory::DoLoopHelper::createLoop(mlir::Value lb, mlir::Value ub,
34                                        const BodyGenerator &bodyGenerator) {
35   return createLoop(
36       lb, ub, builder.createIntegerConstant(loc, builder.getIndexType(), 1),
37       bodyGenerator);
38 }
39 
40 fir::DoLoopOp
createLoop(mlir::Value count,const BodyGenerator & bodyGenerator)41 fir::factory::DoLoopHelper::createLoop(mlir::Value count,
42                                        const BodyGenerator &bodyGenerator) {
43   auto indexType = builder.getIndexType();
44   auto zero = builder.createIntegerConstant(loc, indexType, 0);
45   auto one = builder.createIntegerConstant(loc, count.getType(), 1);
46   auto up = builder.create<mlir::arith::SubIOp>(loc, count, one);
47   return createLoop(zero, up, one, bodyGenerator);
48 }
49