1*fa26c7ffSMogball //===- SideEffectUtils.cpp - Side Effect Utils ------------------*- C++ -*-===//
2*fa26c7ffSMogball //
3*fa26c7ffSMogball // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*fa26c7ffSMogball // See https://llvm.org/LICENSE.txt for license information.
5*fa26c7ffSMogball // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*fa26c7ffSMogball //
7*fa26c7ffSMogball //===----------------------------------------------------------------------===//
8*fa26c7ffSMogball 
9*fa26c7ffSMogball #include "mlir/Transforms/SideEffectUtils.h"
10*fa26c7ffSMogball #include "mlir/IR/Operation.h"
11*fa26c7ffSMogball #include "mlir/Interfaces/SideEffectInterfaces.h"
12*fa26c7ffSMogball 
13*fa26c7ffSMogball using namespace mlir;
14*fa26c7ffSMogball 
isSideEffectFree(Operation * op)15*fa26c7ffSMogball bool mlir::isSideEffectFree(Operation *op) {
16*fa26c7ffSMogball   if (auto memInterface = dyn_cast<MemoryEffectOpInterface>(op)) {
17*fa26c7ffSMogball     // If the op has side-effects, it cannot be moved.
18*fa26c7ffSMogball     if (!memInterface.hasNoEffect())
19*fa26c7ffSMogball       return false;
20*fa26c7ffSMogball     // If the op does not have recursive side effects, then it can be moved.
21*fa26c7ffSMogball     if (!op->hasTrait<OpTrait::HasRecursiveSideEffects>())
22*fa26c7ffSMogball       return true;
23*fa26c7ffSMogball   } else if (!op->hasTrait<OpTrait::HasRecursiveSideEffects>()) {
24*fa26c7ffSMogball     // Otherwise, if the op does not implement the memory effect interface and
25*fa26c7ffSMogball     // it does not have recursive side effects, then it cannot be known that the
26*fa26c7ffSMogball     // op is moveable.
27*fa26c7ffSMogball     return false;
28*fa26c7ffSMogball   }
29*fa26c7ffSMogball 
30*fa26c7ffSMogball   // Recurse into the regions and ensure that all nested ops can also be moved.
31*fa26c7ffSMogball   for (Region &region : op->getRegions())
32*fa26c7ffSMogball     for (Operation &op : region.getOps())
33*fa26c7ffSMogball       if (!isSideEffectFree(&op))
34*fa26c7ffSMogball         return false;
35*fa26c7ffSMogball   return true;
36*fa26c7ffSMogball }
37