|
| 1 | +// Copyright (c) 2024 CINN Authors. All Rights Reserved. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +#pragma once |
| 16 | +#include <optional> |
| 17 | +#include <vector> |
| 18 | +#include "paddle/cinn/ir/ir.h" |
| 19 | +#include "paddle/cinn/ir/ir_base.h" |
| 20 | + |
| 21 | +namespace cinn { |
| 22 | +namespace common { |
| 23 | + |
| 24 | +template <typename Op> |
| 25 | +inline std::optional<ir::Expr> TryConstFold(ir::Expr a, ir::Expr b); |
| 26 | + |
| 27 | +template <> |
| 28 | +inline std::optional<ir::Expr> TryConstFold<ir::Add>(ir::Expr a, ir::Expr b) { |
| 29 | + const ir::IntImm* pa = a.As<ir::IntImm>(); |
| 30 | + const ir::IntImm* pb = b.As<ir::IntImm>(); |
| 31 | + const auto& rtype = a.type(); |
| 32 | + if (pa && pb) { |
| 33 | + int64_t res = pa->value + pb->value; |
| 34 | + return cinn::common::make_shared<ir::IntImm>(rtype, res); |
| 35 | + } |
| 36 | + if (pa && pa->value == 0) return b; |
| 37 | + if (pb && pb->value == 0) return a; |
| 38 | + return std::nullopt; |
| 39 | +} |
| 40 | + |
| 41 | +template <> |
| 42 | +inline std::optional<ir::Expr> TryConstFold<ir::Sub>(ir::Expr a, ir::Expr b) { |
| 43 | + const ir::IntImm* pa = a.As<ir::IntImm>(); |
| 44 | + const ir::IntImm* pb = b.As<ir::IntImm>(); |
| 45 | + const auto& rtype = a.type(); |
| 46 | + if (pa && pb) { |
| 47 | + int64_t res = pa->value - pb->value; |
| 48 | + return cinn::common::make_shared<ir::IntImm>(rtype, res); |
| 49 | + } |
| 50 | + if (pb && pb->value == 0) return a; |
| 51 | + return std::nullopt; |
| 52 | +} |
| 53 | + |
| 54 | +template <> |
| 55 | +inline std::optional<ir::Expr> TryConstFold<ir::Mul>(ir::Expr a, ir::Expr b) { |
| 56 | + const ir::IntImm* pa = a.As<ir::IntImm>(); |
| 57 | + const ir::IntImm* pb = b.As<ir::IntImm>(); |
| 58 | + const auto& rtype = a.type(); |
| 59 | + if (pa && pb) { |
| 60 | + int64_t res = pa->value * pb->value; |
| 61 | + return cinn::common::make_shared<ir::IntImm>(rtype, res); |
| 62 | + } |
| 63 | + if (pa) { |
| 64 | + if (pa->value == 1) return b; |
| 65 | + if (pa->value == 0) return a; |
| 66 | + } |
| 67 | + if (pb) { |
| 68 | + if (pb->value == 1) return a; |
| 69 | + if (pb->value == 0) return b; |
| 70 | + } |
| 71 | + return std::nullopt; |
| 72 | +} |
| 73 | + |
| 74 | +} // namespace common |
| 75 | +} // namespace cinn |
0 commit comments