op_gen.py 73.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os

import yaml

# =====================================
# String Template for h file code gen
# =====================================
NAMESPACE_GARD_TEMPLATE = """namespace {namespace} {{
{input}
}} // namespace {namespace}"""

H_FILE_TEMPLATE = """#ifdef GET_OP_LIST
#undef GET_OP_LIST
{op_declare}
#else
31
// This file is generated by "paddle/fluid/ir/dialect/op_gen.py"
32

33 34
#include <vector>

35 36
#include "paddle/ir/core/builder.h"
#include "paddle/ir/core/operation_utils.h"
37
#include "paddle/ir/core/op_base.h"
38
#include "paddle/fluid/ir/dialect/utils.h"
39
#include "paddle/fluid/ir/dialect/op_yaml_info_util.h"
40
#include "paddle/fluid/ir/interface/op_yaml_info.h"
41
#include "paddle/fluid/ir/interface/infershape.h"
H
hong 已提交
42 43 44
#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/phi/core/infermeta_utils.h"

45
{input}
46 47

{declare_type_id}
48 49 50 51 52 53
#endif
"""

GET_OP_LIST_TEMPALTE = """{}
"""

54 55 56 57
DECLARE_OP_TYPE_ID = """
IR_DECLARE_EXPLICIT_TYPE_ID({op_name})
"""

58 59 60 61 62 63 64
OP_DECLARE_TEMPLATE = """
class {op_name} : public ir::Op<{op_name}{interfaces}{traits}> {{
 public:
  using Op::Op;
  static const char *name() {{ return "{dialect_op_name}"; }}
  {attribute_declare}
  static constexpr uint32_t attributes_num = {attribute_num};
65
  static OpInfoTuple GetOpInfo();
66
  static void Build({build_args});
67
  {build_mutable_attr_is_input}
68
  static void Verify(const std::vector<ir::OpResult> &inputs, const std::vector<ir::Type> &outputs, const ir::AttributeMap &attributes);
69
{get_inputs_and_outputs}
H
hong 已提交
70
{exclusive_interface}
71 72 73 74 75 76 77 78 79
}};
"""
op_0_attribute_declare_str = (
    "static constexpr const char **attributes_name = nullptr;"
)
op_n_attribute_declare_str = (
    "static const char *attributes_name[{attribute_num}];"
)

80
OP_GET_INPUT_TEMPLATE = """  ir::OpOperand {input_name}() {{ return operation()->operand({input_index}); }}
81
"""
82
OP_GET_OUTPUT_TEMPLATE = """  ir::OpResult {output_name}() {{ return operation()->result({output_index}); }}
83 84 85 86 87
"""

# =====================================
# String Template for cc file code gen
# =====================================
88 89 90
CC_FILE_TEMPLATE = """// This file is generated by "paddle/fluid/ir/dialect/op_gen.py"

#include "{h_file}"
91 92
#include "paddle/fluid/ir/dialect/pd_type.h"
#include "paddle/fluid/ir/dialect/pd_attribute.h"
93 94
#include "paddle/ir/core/builtin_attribute.h"
#include "paddle/ir/core/builtin_type.h"
95
#include "paddle/ir/core/builtin_op.h"
96
#include "paddle/ir/core/ir_context.h"
97
#include "paddle/phi/core/enforce.h"
98 99 100 101 102 103 104
#include "paddle/phi/core/dense_tensor.h"
#include "paddle/phi/infermeta/binary.h"
#include "paddle/phi/infermeta/multiary.h"
#include "paddle/phi/infermeta/nullary.h"
#include "paddle/phi/infermeta/unary.h"
#include "paddle/phi/infermeta/ternary.h"
#include "paddle/phi/infermeta/backward.h"
105
#include "paddle/phi/api/lib/utils/allocator.h"
106

107
{input}
108 109

{define_type_id}
110 111 112 113 114 115
"""

OP_N_ATTRIBUTE_DEFINED_TEMPLATE = """
const char *{op_name}::attributes_name[{attribute_num}] = {{ {attribute_names} }};
"""

116
# get op info
117 118
OP_INFO_TEMPLATE = """
OpInfoTuple {op_name}::GetOpInfo() {{
119 120 121
  std::vector<paddle::dialect::OpInputInfo> inputs = {{ {inputs} }};
  std::vector<paddle::dialect::OpAttributeInfo> attributes = {{ {attributes} }};
  std::vector<paddle::dialect::OpOutputInfo> outputs = {{ {outputs} }};
122 123
  paddle::dialect::OpRunTimeInfo run_time_info = OpRunTimeInfo("{infer_meta_func}", {{"{infer_meta_param}"}}, {{"{kernel_func}"}}, {{"{kernel_param}"}}, {{"{kernel_key_dtype}"}}, {{{inplace}}}, {{{view}}});

124
  return std::make_tuple(inputs, attributes, outputs, run_time_info);
125 126
}}
"""
127
CONSTRUCT_INPUT_INFO_TEMPLATE = """OpInputInfo("{name}", "{typename}", {optional}, {no_need_buffer}, {is_mutable_attribute})"""
128 129 130 131 132 133 134
CONSTRUCT_OUTPUT_INFO_TEMPLATE = (
    """OpOutputInfo("{name}", "{typename}", {optional}, {intermediate})"""
)
CONSTRUCT_ATTRIBUTE_INFO_TEMPLATE = (
    """OpAttributeInfo("{name}", "{typename}", "{data_type}")"""
)

135 136
# build
OP_BUILD_TEMPLATE = """
137
void {op_name}::Build({build_args}) {{
138
{build_mutable_attributes}
139 140 141 142 143 144
{build_inputs}
{build_attributes}
{build_outputs}
}}
"""

145
# verify
146
OP_VERIFY_TEMPLATE = """
147
void {op_name}::Verify(const std::vector<ir::OpResult> &inputs, const std::vector<ir::Type> &outputs, const ir::AttributeMap &attributes) {{
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
  VLOG(4) << "Verifying inputs, outputs and attributes for: {op_name}.";

  // Verify inputs type:
  PADDLE_ENFORCE_EQ(inputs.size(), {inputs_size},
                    phi::errors::PreconditionNotMet("The size %d of inputs must be equal to {inputs_size}.", inputs.size()));
  {inputs_type_check}
  // Verify outputs type:
  PADDLE_ENFORCE_EQ(outputs.size(), {outputs_size},
                    phi::errors::PreconditionNotMet("The size %d of outputs must be equal to {outputs_size}.", outputs.size()));
  {outputs_type_check}
  // Verify if attributes contain attribute name in attributes_name:
  {attributes_check}
}}
"""

163
GRAD_OP_VERIFY_TEMPLATE = """
164
void {op_name}::Verify(const std::vector<ir::OpResult> &inputs, const std::vector<ir::Type> &outputs, const ir::AttributeMap &attributes) {{
165 166 167 168 169 170
  (void)inputs;
  (void)outputs;
  (void)attributes;
}}
"""

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
INPUT_TYPE_CHECK_TEMPLATE = """PADDLE_ENFORCE_EQ(inputs[{index}].type().isa<{standard}>(), true,
                    phi::errors::PreconditionNotMet("Type validation failed for the {index}th input."));
  """
INPUT_VECTORTYPE_CHECK_TEMPLATE = """if (inputs[{index}].type().isa<ir::VectorType>()) {{
    for (size_t i = 0; i < inputs[{index}].type().dyn_cast<ir::VectorType>().size(); i++) {{
      PADDLE_ENFORCE_EQ(inputs[{index}].type().dyn_cast<ir::VectorType>()[i].isa<{standard}>(), true,
                        phi::errors::PreconditionNotMet("Type validation failed for the {index}th input."));
    }}
  }} else {{
    PADDLE_ENFORCE_EQ(inputs[{index}].type().isa<{standard}>(), true,
                      phi::errors::PreconditionNotMet("Type validation failed for the {index}th input."));
  }}
  """
INPUT_OPTIONAL_TYPE_CHECK_TEMPLATE = """if (inputs[{index}]) {{
    PADDLE_ENFORCE_EQ(inputs[{index}].type().isa<{standard}>(), true,
                      phi::errors::PreconditionNotMet("Type validation failed for the {index}th input."));
  }}
  """
INPUT_OPTIONAL_VECTORTYPE_CHECK_TEMPLATE = """if (inputs[{index}]) {{
    if (inputs[{index}].type().isa<ir::VectorType>()) {{
      for (size_t i = 0; i < inputs[{index}].type().dyn_cast<ir::VectorType>().size(); i++) {{
        PADDLE_ENFORCE_EQ(inputs[{index}].type().dyn_cast<ir::VectorType>()[i].isa<{standard}>(), true,
                          phi::errors::PreconditionNotMet("Type validation failed for the {index}th input."));
      }}
    }} else {{
      PADDLE_ENFORCE_EQ(inputs[{index}].type().isa<{standard}>(), true,
                        phi::errors::PreconditionNotMet("Type validation failed for the {index}th input."));
    }}
  }}
  """

OUTPUT_TYPE_CHECK_TEMPLATE = """PADDLE_ENFORCE_EQ(outputs[{index}].isa<{standard}>(), true,
                    phi::errors::PreconditionNotMet("Type validation failed for the {index}th output."));
  """
OUTPUT_VECTORTYPE_CHECK_TEMPLATE = """if (outputs[{index}].isa<ir::VectorType>()) {{
    for (size_t i = 0; i < outputs[{index}].dyn_cast<ir::VectorType>().size(); i++) {{
      PADDLE_ENFORCE_EQ(outputs[{index}].dyn_cast<ir::VectorType>()[i].isa<{standard}>(), true,
                        phi::errors::PreconditionNotMet("Type validation failed for the {index}th output."));
    }}
  }} else {{
    PADDLE_ENFORCE_EQ(outputs[{index}].isa<{standard}>(), true,
                      phi::errors::PreconditionNotMet("Type validation failed for the {index}th output."));
  }}
  """
OUTPUT_OPTIONAL_TYPE_CHECK_TEMPLATE = """if (outputs[{index}]) {{
    PADDLE_ENFORCE_EQ(outputs[{index}].isa<{standard}>(), true,
                      phi::errors::PreconditionNotMet("Type validation failed for the {index}th output."));
  }}
  """
OUTPUT_OPTIONAL_VECTORTYPE_CHECK_TEMPLATE = """if (outputs[{index}]) {{
    if (outputs[{index}].isa<ir::VectorType>()) {{
      for (size_t i = 0; i < outputs[{index}].dyn_cast<ir::VectorType>().size(); i++) {{
        PADDLE_ENFORCE_EQ(outputs[{index}].dyn_cast<ir::VectorType>()[i].isa<{standard}>(), true,
                          phi::errors::PreconditionNotMet("Type validation failed for the {index}th output."));
      }}
    }} else {{
      PADDLE_ENFORCE_EQ(outputs[{index}].isa<{standard}>(), true,
                        phi::errors::PreconditionNotMet("Type validation failed for the {index}th output."));
    }}
  }}
  """

233
ATTRIBUTE_CHECK_TEMPLATE = """PADDLE_ENFORCE_EQ(attributes.count("{attribute_name}")>0 && attributes.at("{attribute_name}").isa<{standard}>(), true,
234 235
                    phi::errors::PreconditionNotMet("Type of attribute: {attribute_name} is not right."));
  """
236
ATTRIBUTE_VECTOR_CHECK_TEMPLATE = """PADDLE_ENFORCE_EQ(attributes.count("{attribute_name}")>0 && attributes.at("{attribute_name}").isa<ir::ArrayAttribute>(), true,
237 238 239 240 241 242
                    phi::errors::PreconditionNotMet("Type of attribute: {attribute_name} is not right."));
  for (size_t i = 0; i < attributes.at("{attribute_name}").dyn_cast<ir::ArrayAttribute>().size(); i++) {{
    PADDLE_ENFORCE_EQ(attributes.at("{attribute_name}").dyn_cast<ir::ArrayAttribute>()[i].isa<{standard}>(), true,
                      phi::errors::PreconditionNotMet("Type of attribute: {attribute_name} is not right."));
  }}
  """
H
hong 已提交
243 244 245 246 247 248
OP_INFER_SHAPE_TEMPLATE = """
void {op_name}::InferShape( phi::InferMetaContext *infer_meta ) {{
  auto fn = PD_INFER_META(phi::{infer_meta_func});
  fn(infer_meta);
}}
"""
249

250 251 252 253
DEFINE_OP_TYPE_ID = """
IR_DEFINE_EXPLICIT_TYPE_ID({op_name})
"""

254

255 256 257 258 259 260 261 262 263 264 265 266
def to_phi_and_fluid_op_name(op_item):
    # Templat: - op : phi_name (fluid_name)
    names = op_item.split('(')
    if len(names) == 1:
        phi_fluid_name = names[0].strip()
        return phi_fluid_name, phi_fluid_name
    else:
        phi_name = names[0].strip()
        fluid_name = names[1].split(')')[0].strip()
        return phi_name, fluid_name


267
scalar_type_maps = {
Z
zhangbo9674 已提交
268 269
    'int': 'ir::Int32Attribute',
    'int64_t': 'ir::Int64Attribute',
270 271 272 273 274 275
    'float': 'ir::FloatAttribute',
    'dobule': 'ir::DoubleAttribute',
    'bool': 'ir::BoolAttribute',
}


276
# =====================================
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
# Parse Op Compat From Yaml
# =====================================
class OpCompatParser:
    def __init__(self, ops_compat_yaml_file):
        self.ops_compat_yaml_file = ops_compat_yaml_file
        with open(self.ops_compat_yaml_file, "r") as f:
            self.ops_compat = yaml.safe_load(f)

    def get_compat(self, op_name):
        for compat in self.ops_compat:
            phi_name, fluid_name = to_phi_and_fluid_op_name(compat['op'])
            if op_name == phi_name:
                return compat
        return None


# =====================================
# Parse Op Information From Yaml
295 296
# =====================================
class OpInfoParser:
297
    def __init__(self, op_yaml_item, op_compat_item):
298
        self.op_yaml_item = op_yaml_item
299
        self.op_compat_item = op_compat_item
300
        self.op_phi_name = self.parse_op_phi_name()
301
        # parse inputs
302 303 304
        self.input_name_list = self.parse_input_name_list()
        self.input_type_list = self.parse_input_type_list()
        self.input_optional_list = self.parse_input_optional_list()
305
        self.input_no_need_buffer_list = self.parse_input_no_need_buffer_list()
306 307 308
        self.cross_check(
            self.input_name_list, self.input_type_list, self.input_optional_list
        )
309

310
        # parse outputs
311 312
        self.output_name_list = self.parse_output_name_list()
        self.output_type_list = self.parse_output_type_list()
313
        self.output_size_list = self.parse_output_size_list()
314
        self.output_optional_list = self.parse_output_optional_list()
315
        self.output_intermediate_list = self.parse_output_intermediate_list()
316 317 318 319 320
        self.cross_check(
            self.output_name_list,
            self.output_type_list,
            self.output_optional_list,
        )
321

322
        # parse attributes
323 324 325
        self.attr_types_map = {
            'IntArray': ['paddle::dialect::IntArrayAttribute', 'IntArray'],
            'Scalar': ['paddle::dialect::ScalarAttribute', 'Scalar'],
Z
zhangbo9674 已提交
326 327
            'Scalar(int)': ['ir::Int32Attribute', 'int'],
            'Scalar(int64_t)': ['ir::Int64Attribute', 'int64_t'],
328 329
            'Scalar(float)': ['ir::FloatAttribute', 'float'],
            'Scalar(dobule)': ['ir::DoubleAttribute', 'dobule'],
330 331
            'Scalar[]': [
                'ir::ArrayAttribute<paddle::dialect::ScalarAttribute>',
332
                'const std::vector<Scalar>&',
333
            ],
Z
zhangbo9674 已提交
334 335 336
            'int': ['ir::Int32Attribute', 'int'],
            'int32_t': ['ir::Int32Attribute', 'int32_t'],
            'int64_t': ['ir::Int64Attribute', 'int64_t'],
337 338 339 340 341
            'long': ['ir::LongAttribute', 'long'],
            'size_t': ['ir::Size_tAttribute', 'size_t'],
            'float': ['ir::FloatAttribute', 'float'],
            'float[]': [
                'ir::ArrayAttribute<ir::FloatAttribute>',
342
                'const std::vector<float>&',
343 344 345 346 347
            ],
            'double': ['ir::DoubleAttribute', 'double'],
            'bool': ['ir::BoolAttribute', 'bool'],
            'bool[]': [
                'ir::ArrayAttribute<ir::BoolAttribute>',
348
                'const std::vecot<bool>&',
349 350 351 352
            ],
            'str': ['ir::StrAttribute', 'std::string'],
            'str[]': [
                'ir::ArrayAttribute<ir::StrAttribute>',
353
                'const std::vector<std::string>&',
354 355 356 357 358 359 360 361
            ],
            'Place': ['paddle::dialect::PlaceAttribute', 'Place'],
            'DataLayout': [
                'paddle::dialect::DataLayoutAttribute',
                'DataLayout',
            ],
            'DataType': ['paddle::dialect::DataTypeAttribute', 'DataType'],
            'int64_t[]': [
Z
zhangbo9674 已提交
362
                'ir::ArrayAttribute<ir::Int64Attribute>',
363
                'const std::vector<int64_t>&',
364 365
            ],
            'int[]': [
Z
zhangbo9674 已提交
366
                'ir::ArrayAttribute<ir::Int32Attribute>',
367
                'const std::vector<int>&',
368 369
            ],
        }
370 371
        self.attribute_name_list = self.parse_attribute_name_list()
        self.attribute_type_list = self.parse_attribute_type_list()
372 373 374
        self.attribute_build_arg_type_list = (
            self.parse_attribute_build_arg_type_list()
        )
375
        self.attribute_data_type_list = self.parse_attribute_data_type_list()
376 377 378
        self.attribute_default_value_list = (
            self.parse_attribute_default_value_list()
        )
379 380
        self.cross_check(self.attribute_name_list, self.attribute_type_list)

381 382 383 384 385 386
        # parse mutable attributes (as inputs)
        (
            self.mutable_attribute_name_list,
            self.mutable_attribute_type_list,
        ) = self.parse_mutable_attribute()

387 388 389 390 391 392 393 394
        (
            self.non_mutable_attribute_name_list,
            self.non_mutable_attribute_type_list,
            self.non_mutable_attribute_data_type_list,
            self.non_mutable_attribute_build_arg_type_list,
            self.non_mutable_attribute_default_value_list,
        ) = self.parse_non_nutable_attribute()

395 396 397
        # parse infermeta && kernel
        self.infer_meta_map = self.parse_infer_meta_map()
        self.kernel_map = self.parse_kernel_map()
H
hong 已提交
398 399 400 401 402
        if 'infer_meta' in self.op_yaml_item:
            self.infer_shape_func = self.op_yaml_item['infer_meta']["func"]
        else:
            self.infer_shape_func = None

403 404 405 406
        # parse inplace && view
        self.inplace_map = self.parse_op_inplace_info()
        self.view_map = self.parse_op_view_info()

407 408 409 410 411 412 413 414 415
    def cross_check(self, name_list, type_list, optional_list=None):
        assert len(name_list) == len(
            type_list
        ), "name list size != type list size."
        if optional_list is not None:
            assert len(type_list) == len(
                optional_list
            ), "type list size != optional list size."

416
    def parse_op_phi_name(self):
417 418 419
        if (self.parse_op_inplace_info() is None) and (
            self.parse_op_view_info() is None
        ):
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
            return [self.op_yaml_item['name']]
        else:
            if self.op_yaml_item['name'][-1] == "_":
                return [self.op_yaml_item['name']]
            else:
                return [
                    self.op_yaml_item['name'],
                    self.op_yaml_item['name'] + "_",
                ]

    def parse_op_inplace_info(self):
        if 'inplace' in self.op_yaml_item:
            return self.op_yaml_item['inplace']
        return None

435 436 437 438 439
    def parse_op_view_info(self):
        if 'view' in self.op_yaml_item:
            return self.op_yaml_item['view']
        return None

440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
    def parse_mutable_attribute(self):
        """
        {'axis': 'paddle::dialect::ScalarAttribute', 'rotl': 'paddle::dialect::IntArrayAttribute'}
        """
        mutable_attribute_name_list = []
        mutable_attribute_type_list = []
        # scalar
        if (self.op_compat_item is not None) and (
            'scalar' in self.op_compat_item
        ):
            for scalar_attr in self.op_compat_item['scalar'].keys():
                if 'data_type' in self.op_compat_item['scalar'][scalar_attr]:
                    if (
                        self.op_compat_item['scalar'][scalar_attr]['data_type']
                        == "std::string"
                    ):
                        # see isclose and allclose in op_compat.yaml
                        mutable_attribute_name_list.append(scalar_attr)
                        mutable_attribute_type_list.append(
                            ["ir::StrAttribute", "std::string"]
                        )
                    else:
462 463 464 465 466 467 468
                        if (
                            scalar_attr == "depth"
                            and self.op_phi_name[0] == "one_hot"
                        ):
                            mutable_attribute_name_list.append("num_classes")
                        else:
                            mutable_attribute_name_list.append(scalar_attr)
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
                        mutable_attribute_type_list.append(
                            [
                                "paddle::dialect::ScalarAttribute",
                                self.op_compat_item['scalar'][scalar_attr][
                                    'data_type'
                                ],
                            ]
                        )
                # See eye in op_compat.yaml
                else:
                    mutable_attribute_name_list.append(scalar_attr)
                    mutable_attribute_type_list.append(
                        [
                            "paddle::dialect::ScalarAttribute",
                            self.attribute_data_type_list[
                                self.attribute_name_list.index(scalar_attr)
                            ],
                        ]
                    )

        # int_array
        if (self.op_compat_item is not None) and (
            'int_array' in self.op_compat_item
        ):
            for int_array_attr in self.op_compat_item['int_array']:
                mutable_attribute_name_list.append(int_array_attr)
                mutable_attribute_type_list.append(
                    [
                        "paddle::dialect::IntArrayAttribute",
                        self.op_compat_item['int_array'][int_array_attr][
                            'data_type'
                        ],
                    ]
                )
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
        sorted_mutable_attribute_name_list = []
        sorted_mutable_attribute_type_list = []
        for attr_name in self.attribute_name_list:
            if attr_name in mutable_attribute_name_list:
                sorted_mutable_attribute_name_list.append(attr_name)
                sorted_mutable_attribute_type_list.append(
                    mutable_attribute_type_list[
                        mutable_attribute_name_list.index(attr_name)
                    ]
                )

        return (
            sorted_mutable_attribute_name_list,
            sorted_mutable_attribute_type_list,
        )

    def parse_non_nutable_attribute(self):
        op_non_mutable_attribute_name_list = []
        op_non_mutable_attribute_type_list = []
        op_non_mutable_attribute_data_type_list = []
        op_non_mutable_attribute_build_arg_type_list = []
        op_non_mutable_attribute_default_value_list = []
        for idx in range(len(self.attribute_name_list)):
            if (
                self.attribute_name_list[idx]
                not in self.mutable_attribute_name_list
            ):
                op_non_mutable_attribute_name_list.append(
                    self.attribute_name_list[idx]
                )
                op_non_mutable_attribute_type_list.append(
                    self.attribute_type_list[idx]
                )
                op_non_mutable_attribute_data_type_list.append(
                    self.attribute_data_type_list[idx]
                )
                op_non_mutable_attribute_build_arg_type_list.append(
                    self.attribute_build_arg_type_list[idx]
                )
                op_non_mutable_attribute_default_value_list.append(
                    self.attribute_default_value_list[idx]
                )
        return (
            op_non_mutable_attribute_name_list,
            op_non_mutable_attribute_type_list,
            op_non_mutable_attribute_data_type_list,
            op_non_mutable_attribute_build_arg_type_list,
            op_non_mutable_attribute_default_value_list,
        )
552

553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
    def parse_input_name_list(self):
        name_list = []
        for input_info in self.op_yaml_item['inputs']:
            name_list.append(input_info['name'])
        return name_list

    def parse_input_type_list(self):
        input_types_map = {
            'Tensor': 'paddle::dialect::DenseTensorType',
            'Tensor[]': 'ir::VectorType<paddle::dialect::DenseTensorType>',
        }
        type_list = []
        for input_info in self.op_yaml_item['inputs']:
            assert (
                input_info['typename'] in input_types_map
            ), f"{self.op_phi_name} : Input type error: the input type only support Tensor and Tensor[], but now is {input_info['typename']}."
            type_list.append(input_types_map[input_info['typename']])
        return type_list

    def parse_input_optional_list(self):
        optional_list = []
        for input_info in self.op_yaml_item['inputs']:
575 576 577 578
            if input_info['optional']:
                optional_list.append("true")
            else:
                optional_list.append("false")
579 580
        return optional_list

581 582 583 584 585 586 587 588 589
    def parse_input_no_need_buffer_list(self):
        no_need_buffer_list = []
        for input_info in self.op_yaml_item['inputs']:
            if input_info['no_need_buffer']:
                no_need_buffer_list.append("true")
            else:
                no_need_buffer_list.append("false")
        return no_need_buffer_list

590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
    def parse_output_name_list(self):
        name_list = []
        for output_info in self.op_yaml_item['outputs']:
            name_list.append(output_info['name'])
        return name_list

    def parse_output_type_list(self):
        output_type_map = {
            'Tensor': 'paddle::dialect::DenseTensorType',
            'Tensor[]': 'ir::VectorType<paddle::dialect::DenseTensorType>',
        }
        type_list = []
        for output_info in self.op_yaml_item['outputs']:
            assert (
                output_info['typename'] in output_type_map
            ), f"{self.op_phi_name} : Output type error: the output type only support Tensor and Tensor[], but now is {output_info['typename']}."
            type_list.append(output_type_map[output_info['typename']])
        return type_list

609 610 611 612 613 614 615 616 617
    def parse_output_size_list(self):
        size_list = []
        for output_info in self.op_yaml_item['outputs']:
            if 'size' in output_info:
                size_list.append(output_info['size'])
            else:
                size_list.append(None)
        return size_list

618 619 620 621
    def parse_output_optional_list(self):
        optional_list = []
        for output_info in self.op_yaml_item['outputs']:
            if 'optional' in output_info:
622 623 624 625
                if output_info['optional']:
                    optional_list.append("true")
                else:
                    optional_list.append("false")
626
            else:
627
                optional_list.append("false")
628 629
        return optional_list

630 631 632 633 634 635 636 637 638 639 640 641
    def parse_output_intermediate_list(self):
        intermediate_list = []
        for output_info in self.op_yaml_item['outputs']:
            if 'intermediate' in output_info:
                if output_info['intermediate']:
                    intermediate_list.append("true")
                else:
                    intermediate_list.append("false")
            else:
                intermediate_list.append("false")
        return intermediate_list

642 643 644 645 646 647
    def parse_attribute_name_list(self):
        name_list = []
        for attribute_info in self.op_yaml_item['attrs']:
            name_list.append(attribute_info['name'])
        return name_list

648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
    def parse_attribute_build_arg_type_list(self):
        type_list = []
        for attribute_info in self.op_yaml_item['attrs']:
            assert (
                attribute_info['typename'] in self.attr_types_map
            ), f"{self.op_phi_name} : Attr type error."

            # Scalar & IntArray has data_type
            temp_type = self.attr_types_map[attribute_info['typename']][1]
            if 'Scalar' in temp_type:
                if 'data_type' in attribute_info:
                    temp_type = attribute_info['data_type']
            if 'IntArray' in temp_type:
                if 'data_type' in attribute_info:
                    temp_type = attribute_info['data_type']
            type_list.append(self.get_phi_dtype_name(temp_type))
        return type_list

666 667 668 669
    def parse_attribute_type_list(self):
        type_list = []
        for attribute_info in self.op_yaml_item['attrs']:
            assert (
670
                attribute_info['typename'] in self.attr_types_map
671
            ), f"{self.op_phi_name} : Attr type error."
672
            type_list.append(self.attr_types_map[attribute_info['typename']][0])
673 674
        return type_list

675 676 677 678 679 680 681 682 683
    def parse_attribute_data_type_list(self):
        data_type_list = []
        for attribute_info in self.op_yaml_item['attrs']:
            if 'data_type' in attribute_info:
                data_type_list.append(attribute_info['data_type'])
            else:
                data_type_list.append("")
        return data_type_list

684 685 686 687 688 689 690 691
    def parse_attribute_default_value_list(self):
        default_value_list = []
        for attribute_info in self.op_yaml_item['attrs']:
            if 'default_value' in attribute_info:
                default_value = attribute_info['default_value']
                default_value_list.append(
                    self.get_phi_dtype_name(default_value)
                )
692
            else:
693 694
                default_value_list.append(None)
        return default_value_list
695

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
    def parse_infer_meta_map(self):
        if 'infer_meta' in self.op_yaml_item:
            return self.op_yaml_item['infer_meta']
        else:
            return None

    def parse_kernel_map(self):
        if 'kernel' in self.op_yaml_item:
            return self.op_yaml_item['kernel']
        else:
            return None

    def get_phi_dtype_name(self, name):
        name = name.replace('Scalar', 'phi::Scalar')
        name = name.replace('IntArray', 'phi::IntArray')
        name = name.replace('DataLayout', 'phi::DataLayout')
        name = name.replace('DataType', 'phi::DataType')
        if name.startswith(
            (
                "Place",
                "CPUPlace",
                "GPUPlace",
                "GPUPinnedPlace",
                "XPUPlace",
                "IPUPlace",
                "CustomPlace",
            )
        ):
            return "phi::" + name
        return name
726 727 728 729 730 731 732 733 734 735 736


def to_pascal_case(s):
    words = s.split("_")
    if s[-1] == "_":
        return "".join([word.capitalize() for word in words]) + "_"
    else:
        return "".join([word.capitalize() for word in words]) + ""


# =====================================
737
# Generate Op Definition Files
738
# =====================================
739 740
def GenBuildInputArgsStr(
    op_input_name_list,
741 742 743
    op_attribute_name_list,
    op_attribute_build_arg_type_list,
    op_attribute_default_value_list,
744 745 746 747
    op_mutable_attribute_name_list,
    op_non_mutable_attribute_name_list,
    op_non_mutable_attribute_build_arg_type_list,
    op_non_mutable_attribute_default_value_list,
748
    for_func_define=True,
749
    mutable_attr_is_input=False,
750 751
):
    '''
752
    Example: ir::Builder &builder, ir::OperationArgument &argument, ir::OpResult x_, phi::DataType dtype=phi::DataType::UNDEFINED, phi::Place place={}
753
    '''
754
    # add inputs
755
    build_args_str = "ir::Builder &builder, ir::OperationArgument &argument"
756 757 758
    if len(op_input_name_list) > 0:
        for input_name in op_input_name_list:
            build_args_str += ", ir::OpResult " + input_name + "_"
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795

    if not mutable_attr_is_input:
        # add attributes
        for attr_idx in range(len(op_attribute_name_list)):
            build_args_str += (
                ", "
                + op_attribute_build_arg_type_list[attr_idx]
                + " "
                + op_attribute_name_list[attr_idx]
            )
            if for_func_define:
                if op_attribute_default_value_list[attr_idx] is not None:
                    default_value = op_attribute_default_value_list[attr_idx]
                    if (
                        op_attribute_build_arg_type_list[attr_idx]
                        != "std::string"
                    ):
                        if default_value[0] == "'" or default_value[0] == '"':
                            default_value = default_value[1:]
                        if default_value[-1] == "'" or default_value[-1] == '"':
                            default_value = default_value[0:-1]
                    build_args_str += "=" + default_value
    else:
        # add mutable attributes as inputs
        if len(op_mutable_attribute_name_list) > 0:
            for mutable_attr in op_mutable_attribute_name_list:
                build_args_str += ", ir::OpResult " + mutable_attr + "_"

        # add non-mutable attributes
        for attr_idx in range(len(op_non_mutable_attribute_name_list)):
            build_args_str += (
                ", "
                + op_non_mutable_attribute_build_arg_type_list[attr_idx]
                + " "
                + op_non_mutable_attribute_name_list[attr_idx]
            )
            if for_func_define:
796
                if (
797 798
                    op_non_mutable_attribute_default_value_list[attr_idx]
                    is not None
799
                ):
800 801 802 803 804 805 806 807 808 809 810 811 812
                    default_value = op_non_mutable_attribute_default_value_list[
                        attr_idx
                    ]
                    if (
                        op_non_mutable_attribute_build_arg_type_list[attr_idx]
                        != "std::string"
                    ):
                        if default_value[0] == "'" or default_value[0] == '"':
                            default_value = default_value[1:]
                        if default_value[-1] == "'" or default_value[-1] == '"':
                            default_value = default_value[0:-1]
                    build_args_str += "=" + default_value

813 814 815
    return build_args_str


816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
mutable_attribute_phi_type_maps = {
    'int': 'phi::DataType::INT32',
    'int64_t': 'phi::DataType::INT64',
    'float': 'phi::DataType::FLOAT32',
    'std::vector<int64_t>': 'phi::DataType::INT64',
    'const std::vector<int64_t>&': 'phi::DataType::INT64',
}


def GenBuildInserFullForMutableAttribute(
    op_attribute_name_list,
    op_attribute_build_arg_type_list,
    op_mutable_attribute_name_list,
    op_mutable_attribute_type_list,
):
    build_mutable_attribute = ""
    BUILD_INTARRAY_ATTRIBUTE_TEMPLATE = """  // Generate int_array mutable attribute: {attr_name}
  paddle::dialect::FullIntArrayOp full_{attr_name}_op = builder.Build<paddle::dialect::FullIntArrayOp>({attr_name}, {phi_dtype}, phi::CPUPlace());
834
  ir::OpResult {attr_name}_ = full_{attr_name}_op->result(0);
835 836 837
    """
    BUILD_SCALAR_ATTRIBUTE_TEMPLATE = """  // Generate scalar mutable attribute: {attr_name}
  paddle::dialect::FullOp full_{attr_name}_op = builder.Build<paddle::dialect::FullOp>(std::vector<int64_t>{{1}}, {attr_name}, {phi_dtype}, phi::CPUPlace());
838
  ir::OpResult {attr_name}_ = full_{attr_name}_op->result(0);
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
    """
    for idx in range(len(op_mutable_attribute_name_list)):
        attr_name = op_mutable_attribute_name_list[idx]
        attr_type = op_mutable_attribute_type_list[idx][0]
        if attr_name in op_attribute_name_list:
            phi_dtype = mutable_attribute_phi_type_maps[
                op_attribute_build_arg_type_list[
                    op_attribute_name_list.index(attr_name)
                ]
            ]
        else:
            phi_dtype = mutable_attribute_phi_type_maps[
                op_mutable_attribute_type_list[idx][1]
            ]
        if attr_type == "paddle::dialect::IntArrayAttribute":
            build_mutable_attribute += BUILD_INTARRAY_ATTRIBUTE_TEMPLATE.format(
                attr_name=attr_name, phi_dtype=phi_dtype
            )
        else:
            build_mutable_attribute += BUILD_SCALAR_ATTRIBUTE_TEMPLATE.format(
                attr_name=attr_name, phi_dtype=phi_dtype
            )
    return build_mutable_attribute


864
def GenBuildInputs(op_input_name_list, op_mutable_attribute_name_list):
865
    BUILD_INPUT_TEMPLATE = """  std::vector<ir::OpResult> argument_inputs = {{{inputs_args}}};
866
  argument.AddOperands(argument_inputs.begin(), argument_inputs.end());
867
"""
868 869 870 871 872 873
    build_input_str = '  VLOG(4) << "Builder construction inputs";\n'
    input_name_list = op_input_name_list + op_mutable_attribute_name_list
    if len(input_name_list) > 0:
        inputs_args_str = ""
        inputs_args_str += "_, ".join(input_name_list) + "_"
        build_input_str += BUILD_INPUT_TEMPLATE.format(
874 875 876 877 878
            inputs_args=inputs_args_str
        )
    return build_input_str


879 880 881
def GenBuildAttributes(
    op_non_mutable_attribute_name_list, op_non_mutable_attribute_type_list
):
882 883
    INTARRAY_STR_TEMPLATE = """  ir::Attribute attr_{attr_name} = {op_attribute_type}::get(ir::IrContext::Instance(), phi::IntArray({attr}));
"""
884
    SCALAR_STR_TEMPLATE = """  ir::Attribute attr_{attr_name} = TransToIrAttribute({attr}, ir::IrContext::Instance());
885 886 887 888 889 890 891 892 893 894
"""
    STR_TEMPLATE = """  ir::Attribute attr_{attr_name} = {op_attribute_type}::get(ir::IrContext::Instance(), {attr});
"""
    ARRAY_ATTRIBUTE_TEMPLATE = """  std::vector<ir::Attribute> vec_{attr_name};
  for (size_t i = 0; i < static_cast<size_t>({attr_size}); i++) {{
    {create_attribute}
    vec_{attr_name}.push_back(attr_{attr_name});
  }}
  ir::Attribute attr_{attr_name} = ir::ArrayAttribute::get(ir::IrContext::Instance(), vec_{attr_name});
"""
895 896 897 898 899 900
    attr_str = '  VLOG(4) << "Builder construction attributes";\n'
    for idx in range(len(op_non_mutable_attribute_name_list)):
        if "ir::ArrayAttribute<" in op_non_mutable_attribute_type_list[idx]:
            inner_attribute_type = op_non_mutable_attribute_type_list[idx][
                19:-1
            ]
901 902
            if inner_attribute_type == "paddle::dialect::IntArrayAttribute":
                attr_str += ARRAY_ATTRIBUTE_TEMPLATE.format(
903 904 905
                    attr_name=op_non_mutable_attribute_name_list[idx],
                    attr_size=op_non_mutable_attribute_name_list[idx]
                    + ".size()",
906
                    create_attribute=INTARRAY_STR_TEMPLATE.format(
907
                        attr_name=op_non_mutable_attribute_name_list[idx],
908
                        op_attribute_type=inner_attribute_type,
909
                        attr=op_non_mutable_attribute_name_list[idx] + "[i]",
910 911 912 913
                    ),
                )
            elif inner_attribute_type == "paddle::dialect::ScalarAttribute":
                attr_str += ARRAY_ATTRIBUTE_TEMPLATE.format(
914 915 916
                    attr_name=op_non_mutable_attribute_name_list[idx],
                    attr_size=op_non_mutable_attribute_name_list[idx]
                    + ".size()",
917
                    create_attribute=SCALAR_STR_TEMPLATE.format(
918 919
                        attr_name=op_non_mutable_attribute_name_list[idx],
                        attr=op_non_mutable_attribute_name_list[idx] + "[i]",
920 921 922 923
                    ),
                )
            else:
                attr_str += ARRAY_ATTRIBUTE_TEMPLATE.format(
924 925 926
                    attr_name=op_non_mutable_attribute_name_list[idx],
                    attr_size=op_non_mutable_attribute_name_list[idx]
                    + ".size()",
927
                    create_attribute=STR_TEMPLATE.format(
928
                        attr_name=op_non_mutable_attribute_name_list[idx],
929
                        op_attribute_type=inner_attribute_type,
930
                        attr=op_non_mutable_attribute_name_list[idx] + "[i]",
931 932 933
                    ),
                )
        elif (
934 935
            op_non_mutable_attribute_type_list[idx]
            == "paddle::dialect::IntArrayAttribute"
936 937
        ):
            attr_str += INTARRAY_STR_TEMPLATE.format(
938 939 940
                attr_name=op_non_mutable_attribute_name_list[idx],
                op_attribute_type=op_non_mutable_attribute_type_list[idx],
                attr=op_non_mutable_attribute_name_list[idx],
941 942
            )

943 944 945 946
        elif (
            op_non_mutable_attribute_type_list[idx]
            == "paddle::dialect::ScalarAttribute"
        ):
947
            attr_str += SCALAR_STR_TEMPLATE.format(
948 949
                attr_name=op_non_mutable_attribute_name_list[idx],
                attr=op_non_mutable_attribute_name_list[idx],
950 951 952
            )
        else:
            attr_str += STR_TEMPLATE.format(
953 954 955
                attr_name=op_non_mutable_attribute_name_list[idx],
                op_attribute_type=op_non_mutable_attribute_type_list[idx],
                attr=op_non_mutable_attribute_name_list[idx],
956
            )
957
        attr_str += """  argument.AddAttribute("{attr_name}", attr_{attr_name});\n""".format(
958
            attr_name=op_non_mutable_attribute_name_list[idx]
959 960 961 962 963 964 965 966
        )

    return attr_str


def GenBuildOutputs(
    op_input_name_list,
    op_input_type_list,
967 968
    op_mutable_attribute_name_list,
    op_mutable_attribute_type_list,
969 970 971 972
    op_output_name_list,
    op_output_type_list,
    op_output_size_list,
    op_infer_meta_map,
973
    mutable_attr_is_input=False,
974
):
975
    build_output_str = '  VLOG(4) << "Builder construction outputs";\n'
976 977 978 979 980 981 982 983 984
    CREATE_INPUT_METATENSOR_TEMPLATE = """
  VLOG(4) << "Builder construction  dense_{name}";
  phi::DenseTensor dense_{name}(std::make_unique<paddle::experimental::DefaultAllocator>(paddle::platform::CPUPlace()).get(),
                                phi::DenseTensorMeta(TransToPhiDataType({name}.dtype()),
                                                     {name}.dims(),
                                                     {name}.data_layout(),
                                                     {name}.lod(),
                                                     {name}.offset()));
  VLOG(4) << "Builder construction  meta_{name}";
985 986
  phi::MetaTensor meta_{name}(&dense_{name});
"""
987
    CREATE_INPUT_VEC_METATENSOR_TEMPLATE = """  std::vector<phi::DenseTensor> vec_dense_{name};
988
  for (size_t i=0; i < static_cast<size_t>({name}.size()); i++) {{
989 990 991 992 993 994 995 996 997
    vec_dense_{name}.push_back(phi::DenseTensor(std::make_unique<paddle::experimental::DefaultAllocator>(paddle::platform::CPUPlace()).get(),
                                                phi::DenseTensorMeta(TransToPhiDataType({name}[i].dyn_cast<paddle::dialect::DenseTensorType>().dtype()),
                                                                     {name}[i].dyn_cast<paddle::dialect::DenseTensorType>().dims(),
                                                                     {name}[i].dyn_cast<paddle::dialect::DenseTensorType>().data_layout(),
                                                                     {name}[i].dyn_cast<paddle::dialect::DenseTensorType>().lod(),
                                                                     {name}[i].dyn_cast<paddle::dialect::DenseTensorType>().offset())));
  }}
  std::vector<phi::MetaTensor> vec_meta_{name};
  for (size_t i=0; i < vec_dense_{name}.size(); i++) {{
998 999
    vec_meta_{name}.push_back(phi::MetaTensor(&vec_dense_{name}[i]));
  }}
1000

1001 1002 1003 1004 1005
  std::vector<const phi::MetaTensor*> meta_{name};
  for (size_t i=0; i < static_cast<size_t>(vec_meta_{name}.size()); i++) {{
    meta_{name}.push_back(&vec_meta_{name}[i]);
  }}
 """
1006

1007 1008 1009
    CREATE_INTARRAY_MUTABLE_ATTRIBUE_TEMPLATE = """  std::vector<int64_t> {name} = {name}_.owner()->dyn_cast<paddle::dialect::FullIntArrayOp>().operation()->attributes().at("value").dyn_cast<paddle::dialect::IntArrayAttribute>().data().GetData(); (void){name};\n"""
    CREATE_SCALAR_MUTABLE_ATTRIBUE_TEMPLATE = """  {dtype} {name} = {name}_.owner()->dyn_cast<paddle::dialect::FullOp>().operation()->attributes().at("value").dyn_cast<paddle::dialect::ScalarAttribute>().data().to<{dtype}>(); (void){name};\n"""

1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    CREATE_OUTPUT_METATENSOR_TEMPLATE = """  phi::DenseTensor dense_{name};
  phi::MetaTensor meta_{name}(&dense_{name});
"""
    CREATE_OUTPUT_VEC_METATENSOR_TEMPLATE = """  std::vector<phi::DenseTensor> vec_dense_{name}(({output_size}), phi::DenseTensor());
  std::vector<phi::MetaTensor> vec_meta_{name};
  for (size_t i=0; i < static_cast<size_t>({output_size}); i++) {{
    vec_meta_{name}.push_back(phi::MetaTensor(&vec_dense_{name}[i]));
  }}
  std::vector<phi::MetaTensor*> meta_{name};
  for (size_t i=0; i < static_cast<size_t>(vec_meta_{name}.size()); i++) {{
    meta_{name}.push_back(&vec_meta_{name}[i]);
  }}
"""
    # Prepar input type
    for idx in range(len(op_input_name_list)):
        # is a vector<Tensor>
        if 'ir::VectorType' in op_input_type_list[idx]:
            build_output_str += "  ir::VectorType {name} = {name}_.type().dyn_cast<ir::VectorType>(); (void){name};\n".format(
                name=op_input_name_list[idx]
            )
        # is a Tensor
        else:
            build_output_str += "  paddle::dialect::DenseTensorType {name} = {name}_.type().dyn_cast<paddle::dialect::DenseTensorType>(); (void){name};\n".format(
                name=op_input_name_list[idx]
            )

1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
    # Prepare mutable attributes
    if mutable_attr_is_input:
        for idx in range(len(op_mutable_attribute_name_list)):
            attr_dtype = op_mutable_attribute_type_list[idx]
            # int_array
            if attr_dtype[0] == "paddle::dialect::IntArrayAttribute":
                build_output_str += (
                    CREATE_INTARRAY_MUTABLE_ATTRIBUE_TEMPLATE.format(
                        name=op_mutable_attribute_name_list[idx]
                    )
                )
            # scalar
            elif attr_dtype[0] == "paddle::dialect::ScalarAttribute":
                build_output_str += (
                    CREATE_SCALAR_MUTABLE_ATTRIBUE_TEMPLATE.format(
                        name=op_mutable_attribute_name_list[idx],
                        dtype=attr_dtype[1],
                    )
                )
            # string
            elif attr_dtype[0] == "ir::StrAttribute":
                build_output_str += ""
            else:
                assert "mutable attribtue type is not right."
        build_output_str += "\n"

1062
    # Prepare inputs_meta_tensor & attributes for infer meta
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
    infer_meta_args = []
    for idx in range(len(op_infer_meta_map['param'])):
        # is input
        if op_infer_meta_map['param'][idx] in op_input_name_list:
            if (
                "meta_" + op_infer_meta_map['param'][idx]
            ) not in infer_meta_args:
                # is a vector<Tensor>
                if (
                    'ir::VectorType'
                    in op_input_type_list[
                        op_input_name_list.index(
                            op_infer_meta_map['param'][idx]
                        )
                    ]
                ):
                    build_output_str += (
                        CREATE_INPUT_VEC_METATENSOR_TEMPLATE.format(
                            name=op_infer_meta_map['param'][idx]
                        )
                    )
                # is a Tensor
                else:
                    build_output_str += CREATE_INPUT_METATENSOR_TEMPLATE.format(
                        name=op_infer_meta_map['param'][idx]
                    )

            infer_meta_args.append("meta_" + op_infer_meta_map['param'][idx])
        # is attribute
        else:
            infer_meta_args.append(op_infer_meta_map['param'][idx])

1095
    # Prepare outputs_meta_tensor for infer meta
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
    for idx in range(len(op_output_name_list)):
        # is a vector<Tensor>
        if 'ir::VectorType' in op_output_type_list[idx]:
            build_output_str += CREATE_OUTPUT_VEC_METATENSOR_TEMPLATE.format(
                name=op_output_name_list[idx],
                output_size=op_output_size_list[idx],
            )
            infer_meta_args.append(f"meta_{op_output_name_list[idx]}")
        # is a Tensor
        else:
            build_output_str += CREATE_OUTPUT_METATENSOR_TEMPLATE.format(
                name=op_output_name_list[idx]
            )
            infer_meta_args.append(f"&meta_{op_output_name_list[idx]}")

    # Execute infer meta function
    CREATE_INFER_META_FUNC_TEMPLATE = """
  phi::{func}({args});
"""
    build_output_str += CREATE_INFER_META_FUNC_TEMPLATE.format(
        func=op_infer_meta_map['func'], args=", ".join(infer_meta_args)
    )

    # use dense_{name} or vec_dense_{name} to create Outputs type
    build_output_str += "\n  std::vector<ir::Type> argument_outputs;"

    CREATE_OUTPUT_DENSE_TENSOR_TEMPLATE = """
  ir::Type {name}_dense_tensor_type = paddle::dialect::DenseTensorType::get(ir::IrContext::Instance(), TransToIrDataType(dense_{name}.dtype()), dense_{name}.dims(), dense_{name}.layout(), dense_{name}.lod(), dense_{name}.offset());
  argument_outputs.push_back({name}_dense_tensor_type);
"""
    CREATE_OUTPUT_VEC_DENSE_TENSOR_TEMPLATE = """
  std::vector<ir::Type> {name}_types;
  for (size_t i=0; i < static_cast<size_t>({output_size}); i++) {{
    {name}_types.push_back(paddle::dialect::DenseTensorType::get(ir::IrContext::Instance(), TransToIrDataType(vec_dense_{name}[i].dtype()), vec_dense_{name}[i].dims(), vec_dense_{name}[i].layout(), vec_dense_{name}[i].lod(), vec_dense_{name}[i].offset()));
  }}
  ir::Type {name}_vector_type = ir::VectorType::get(ir::IrContext::Instance(), {name}_types);
  argument_outputs.push_back({name}_vector_type);
"""
    for idx in range(len(op_output_name_list)):
        # is a vector<Tensor>
        if 'ir::VectorType' in op_output_type_list[idx]:
            build_output_str += CREATE_OUTPUT_VEC_DENSE_TENSOR_TEMPLATE.format(
                name=op_output_name_list[idx],
                output_size=op_output_size_list[idx],
            )
        # is a Tensor
        else:
            build_output_str += CREATE_OUTPUT_DENSE_TENSOR_TEMPLATE.format(
                name=op_output_name_list[idx]
            )

1147
    build_output_str += "  argument.AddTypes(argument_outputs.begin(), argument_outputs.end());\n"
1148 1149 1150 1151

    return build_output_str


1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
def GenBuild(
    op_class_name,
    op_input_name_list,
    op_input_type_list,
    op_attribute_name_list,
    op_attribute_build_arg_type_list,
    op_attribute_default_value_list,
    op_mutable_attribute_name_list,
    op_mutable_attribute_type_list,
    op_non_mutable_attribute_name_list,
    op_non_mutable_attribute_type_list,
    op_non_mutable_attribute_build_arg_type_list,
    op_non_mutable_attribute_default_value_list,
    op_output_name_list,
    op_output_type_list,
    op_output_size_list,
    op_infer_meta_map,
    muta_attr_is_input=False,
):
    build_args_for_declare = ""
    build_func = ""

    build_args_for_declare = GenBuildInputArgsStr(
        op_input_name_list,
        op_attribute_name_list,
        op_attribute_build_arg_type_list,
        op_attribute_default_value_list,
        op_mutable_attribute_name_list,
        op_non_mutable_attribute_name_list,
        op_non_mutable_attribute_build_arg_type_list,
        op_non_mutable_attribute_default_value_list,
        True,
        muta_attr_is_input,
    )

    build_args_for_define = GenBuildInputArgsStr(
        op_input_name_list,
        op_attribute_name_list,
        op_attribute_build_arg_type_list,
        op_attribute_default_value_list,
        op_mutable_attribute_name_list,
        op_non_mutable_attribute_name_list,
        op_non_mutable_attribute_build_arg_type_list,
        op_non_mutable_attribute_default_value_list,
        False,
        muta_attr_is_input,
    )
    inset_full_for_mutable_attributes_str = ""
    if not muta_attr_is_input:
        inset_full_for_mutable_attributes_str = (
            GenBuildInserFullForMutableAttribute(
                op_attribute_name_list,
                op_attribute_build_arg_type_list,
                op_mutable_attribute_name_list,
                op_mutable_attribute_type_list,
            )
        )

    build_inputs_str = GenBuildInputs(
        op_input_name_list, op_mutable_attribute_name_list
    )
    build_attributes_str = GenBuildAttributes(
        op_non_mutable_attribute_name_list,
        op_non_mutable_attribute_type_list,
    )
    build_outputs_str = GenBuildOutputs(
        op_input_name_list,
        op_input_type_list,
        op_mutable_attribute_name_list,
        op_mutable_attribute_type_list,
        op_output_name_list,
        op_output_type_list,
        op_output_size_list,
        op_infer_meta_map,
1226
        muta_attr_is_input,
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
    )

    build_func = OP_BUILD_TEMPLATE.format(
        op_name=op_class_name,
        build_args=build_args_for_define,
        build_mutable_attributes=inset_full_for_mutable_attributes_str,
        build_inputs=build_inputs_str,
        build_attributes=build_attributes_str,
        build_outputs=build_outputs_str,
    )

    return (build_args_for_declare, build_func)


1241 1242
def OpGenerator(
    op_yaml_files,
1243
    op_compat_yaml_file,
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
    namespaces,
    dialect_name,
    op_def_h_file,
    op_def_cc_file,
):
    # (1) Prepare: Delete existing old files: pd_op.h.tmp, pd_op.cc.tmp
    if os.path.exists(op_def_h_file):
        os.remove(op_def_h_file)
    if os.path.exists(op_def_cc_file):
        os.remove(op_def_cc_file)

    # (2) Prepare: Get all op item in all op_yaml_files
1256 1257
    op_compat_parser = OpCompatParser(op_compat_yaml_file)

1258 1259 1260 1261 1262 1263 1264
    op_yaml_items = []
    for yaml_file in op_yaml_files:
        with open(yaml_file, "r") as f:
            ops = yaml.safe_load(f)
            op_yaml_items = op_yaml_items + ops
    op_info_items = []
    for op in op_yaml_items:
1265 1266 1267
        op_info_items.append(
            OpInfoParser(op, op_compat_parser.get_compat(op['name']))
        )
1268 1269 1270 1271 1272 1273

    # (3) CodeGen: Traverse op_info_items and generate
    ops_name_list = []  # all op class name store in this list
    ops_declare_list = []  # all op class declare store in this list
    ops_defined_list = []  # all op class defined store in this list
    for op_info in op_info_items:
1274
        # get op inputs info
1275 1276 1277
        op_input_name_list = op_info.input_name_list
        op_input_type_list = op_info.input_type_list
        op_input_optional_list = op_info.input_optional_list
1278
        op_input_no_need_buffer_list = op_info.input_no_need_buffer_list
1279
        # get op outputs info
1280 1281
        op_output_name_list = op_info.output_name_list
        op_output_type_list = op_info.output_type_list
1282
        op_output_size_list = op_info.output_size_list
1283
        op_output_optional_list = op_info.output_optional_list
1284
        op_output_intermediate_list = op_info.output_intermediate_list
1285 1286 1287 1288
        # get op mutable attribute
        op_mutable_attribute_name_list = op_info.mutable_attribute_name_list
        op_mutable_attribute_type_list = op_info.mutable_attribute_type_list
        # get op attribute
1289 1290
        op_attribute_name_list = op_info.attribute_name_list
        op_attribute_type_list = op_info.attribute_type_list
1291
        op_attribute_data_type_list = op_info.attribute_data_type_list
1292 1293
        op_attribute_build_arg_type_list = op_info.attribute_build_arg_type_list
        op_attribute_default_value_list = op_info.attribute_default_value_list
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
        op_non_mutable_attribute_name_list = (
            op_info.non_mutable_attribute_name_list
        )
        op_non_mutable_attribute_type_list = (
            op_info.non_mutable_attribute_type_list
        )
        op_non_mutable_attribute_data_type_list = (
            op_info.non_mutable_attribute_data_type_list
        )
        op_non_mutable_attribute_build_arg_type_list = (
            op_info.non_mutable_attribute_build_arg_type_list
        )
        op_non_mutable_attribute_default_value_list = (
            op_info.non_mutable_attribute_default_value_list
        )

1310
        # others
1311 1312
        op_infer_meta_map = op_info.infer_meta_map
        op_kernel_map = op_info.kernel_map
1313 1314
        op_inplace_map = op_info.inplace_map
        op_view_map = op_info.view_map
1315
        op_interfaces = ["OpYamlInfoInterface"]
1316 1317
        op_traits = []

H
hong 已提交
1318 1319 1320 1321 1322 1323 1324
        exclusive_interface_str = ""
        if op_info.infer_shape_func:
            op_interfaces += ["InferShapeInterface"]
            exclusive_interface_str += (
                "  static void InferShape( phi::InferMetaContext *infer_meta );"
            )

1325 1326 1327 1328 1329
        # If op has inplace info, we will generate inplace op and non-inplace op.
        for op_name in op_info.op_phi_name:
            op_class_name = to_pascal_case(op_name) + "Op"
            op_dialect_name = dialect_name + "." + op_name

1330 1331 1332
            # =================================== #
            #    gen interface/trait list str     #
            # =================================== #
1333 1334 1335 1336 1337 1338 1339
            op_interfaces_str = ""
            if len(op_interfaces) > 0:
                op_interfaces_str = "," + ",".join(op_interfaces)
            op_traits_str = ""
            if len(op_traits) > 0:
                op_traits_str = "," + ",".join(op_traits)

1340 1341 1342
            # =================================== #
            #  gen get input/output methods str   #
            # =================================== #
1343 1344 1345 1346 1347 1348
            op_get_inputs_outputs_str = ""
            for idx in range(len(op_input_name_list)):
                op_get_inputs_outputs_str += OP_GET_INPUT_TEMPLATE.format(
                    input_name=op_input_name_list[idx],
                    input_index=idx,
                )
1349 1350 1351 1352 1353
            for idx in range(len(op_mutable_attribute_name_list)):
                op_get_inputs_outputs_str += OP_GET_INPUT_TEMPLATE.format(
                    input_name=op_mutable_attribute_name_list[idx],
                    input_index=idx + len(op_input_name_list),
                )
1354 1355 1356 1357 1358
            for idx in range(len(op_output_name_list)):
                op_get_inputs_outputs_str += OP_GET_OUTPUT_TEMPLATE.format(
                    output_name=op_output_name_list[idx],
                    output_index=idx,
                )
1359

1360 1361 1362 1363 1364 1365 1366 1367
            # =================================== #
            #         gen Build methods str       #
            # =================================== #
            build_args_with_muta_attr_not_input_for_declare = ""
            build_func_with_muta_attr_not_input = ""
            build_mutable_attr_is_input = ""
            build_func_with_muta_attr_is_input = ""

1368
            if op_infer_meta_map is not None:
1369 1370 1371 1372 1373
                (
                    build_args_with_muta_attr_not_input_for_declare,
                    build_func_with_muta_attr_not_input,
                ) = GenBuild(
                    op_class_name,
1374
                    op_input_name_list,
1375 1376 1377 1378
                    op_input_type_list,
                    op_attribute_name_list,
                    op_attribute_build_arg_type_list,
                    op_attribute_default_value_list,
1379
                    op_mutable_attribute_name_list,
1380
                    op_mutable_attribute_type_list,
1381
                    op_non_mutable_attribute_name_list,
1382
                    op_non_mutable_attribute_type_list,
1383 1384
                    op_non_mutable_attribute_build_arg_type_list,
                    op_non_mutable_attribute_default_value_list,
1385 1386 1387 1388
                    op_output_name_list,
                    op_output_type_list,
                    op_output_size_list,
                    op_infer_meta_map,
1389
                    muta_attr_is_input=False,
1390
                )
1391
                if len(op_mutable_attribute_name_list) > 0:
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
                    (
                        build_args_with_muta_attr_is_input_for_declare,
                        build_func_with_muta_attr_is_input,
                    ) = GenBuild(
                        op_class_name,
                        op_input_name_list,
                        op_input_type_list,
                        op_attribute_name_list,
                        op_attribute_build_arg_type_list,
                        op_attribute_default_value_list,
                        op_mutable_attribute_name_list,
                        op_mutable_attribute_type_list,
                        op_non_mutable_attribute_name_list,
                        op_non_mutable_attribute_type_list,
                        op_non_mutable_attribute_build_arg_type_list,
                        op_non_mutable_attribute_default_value_list,
                        op_output_name_list,
                        op_output_type_list,
                        op_output_size_list,
                        op_infer_meta_map,
                        muta_attr_is_input=True,
                    )

                    build_mutable_attr_is_input = "static void Build({build_args});".format(
                        build_args=build_args_with_muta_attr_is_input_for_declare
                    )
1418

1419
            # gen op_declare_str/op_defined_str
1420
            if len(op_non_mutable_attribute_name_list) == 0:
1421 1422 1423 1424 1425 1426 1427
                op_declare_str = OP_DECLARE_TEMPLATE.format(
                    op_name=op_class_name,
                    dialect_op_name=op_dialect_name,
                    interfaces=op_interfaces_str,
                    traits=op_traits_str,
                    attribute_declare=op_0_attribute_declare_str,
                    attribute_num=0,
1428 1429
                    build_args=build_args_with_muta_attr_not_input_for_declare,
                    build_mutable_attr_is_input=build_mutable_attr_is_input,
1430
                    get_inputs_and_outputs=op_get_inputs_outputs_str,
H
hong 已提交
1431
                    exclusive_interface=exclusive_interface_str,
1432 1433 1434 1435 1436 1437 1438 1439 1440
                )
                op_defined_str = ""
            else:
                op_declare_str = OP_DECLARE_TEMPLATE.format(
                    op_name=op_class_name,
                    dialect_op_name=op_dialect_name,
                    interfaces=op_interfaces_str,
                    traits=op_traits_str,
                    attribute_declare=op_n_attribute_declare_str.format(
1441
                        attribute_num=len(op_non_mutable_attribute_name_list)
1442
                    ),
1443
                    attribute_num=len(op_non_mutable_attribute_name_list),
1444 1445
                    build_args=build_args_with_muta_attr_not_input_for_declare,
                    build_mutable_attr_is_input=build_mutable_attr_is_input,
1446
                    get_inputs_and_outputs=op_get_inputs_outputs_str,
H
hong 已提交
1447
                    exclusive_interface=exclusive_interface_str,
1448 1449
                )
                attribute_names_str = (
1450
                    '"' + '", "'.join(op_non_mutable_attribute_name_list) + '"'
1451 1452 1453
                )
                op_defined_str = OP_N_ATTRIBUTE_DEFINED_TEMPLATE.format(
                    op_name=op_class_name,
1454
                    attribute_num=len(op_non_mutable_attribute_name_list),
1455 1456
                    attribute_names=attribute_names_str,
                )
1457

1458 1459 1460
            # =================================== #
            #         gen GetOpInfo func str      #
            # =================================== #
1461
            # generate get op info funciton: inputs
1462
            input_info_list = []
1463 1464 1465 1466 1467 1468 1469 1470
            for idx in range(len(op_input_name_list)):
                input_info_list.append(
                    CONSTRUCT_INPUT_INFO_TEMPLATE.format(
                        name=op_input_name_list[idx],
                        typename=op_input_type_list[idx],
                        optional=op_input_optional_list[idx],
                        no_need_buffer=op_input_no_need_buffer_list[idx],
                        is_mutable_attribute='false',
1471
                    )
1472 1473 1474 1475 1476 1477 1478 1479 1480
                )
            for idx in range(len(op_mutable_attribute_name_list)):
                input_info_list.append(
                    CONSTRUCT_INPUT_INFO_TEMPLATE.format(
                        name=op_mutable_attribute_name_list[idx],
                        typename=op_mutable_attribute_type_list[idx][0],
                        optional='false',
                        no_need_buffer='false',
                        is_mutable_attribute='true',
1481
                    )
1482 1483 1484 1485 1486
                )
            if len(input_info_list) > 0:
                inputs_info_str = ", ".join(input_info_list)
            else:
                inputs_info_str = ""
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
            # generate get op info funciton: outputs
            outputs_info_str = ""
            if len(op_output_name_list) > 0:
                output_info_list = []
                for idx in range(len(op_output_name_list)):
                    output_info_list.append(
                        CONSTRUCT_OUTPUT_INFO_TEMPLATE.format(
                            name=op_output_name_list[idx],
                            typename=op_output_type_list[idx],
                            optional=op_output_optional_list[idx],
                            intermediate=op_output_intermediate_list[idx],
                        )
1499
                    )
1500 1501 1502
                outputs_info_str = ", ".join(output_info_list)
            # generate get op info funciton: attributes
            attribute_info_str = ""
1503
            if len(op_non_mutable_attribute_name_list) > 0:
1504
                attribute_info_list = []
1505
                for idx in range(len(op_non_mutable_attribute_name_list)):
1506 1507
                    attribute_info_list.append(
                        CONSTRUCT_ATTRIBUTE_INFO_TEMPLATE.format(
1508 1509 1510 1511 1512
                            name=op_non_mutable_attribute_name_list[idx],
                            typename=op_non_mutable_attribute_type_list[idx],
                            data_type=op_non_mutable_attribute_data_type_list[
                                idx
                            ],
1513
                        )
1514
                    )
1515
                attribute_info_str = ", ".join(attribute_info_list)
1516 1517 1518 1519 1520 1521
            # generate runtiem info
            infer_meta_func_str = ""
            infer_meta_param_str = ""
            if op_infer_meta_map is not None:
                infer_meta_func_str = op_infer_meta_map['func']
                infer_meta_param_str = '", "'.join(op_infer_meta_map['param'])
1522

1523 1524
            kernel_func_str = ""
            kernel_param_str = ""
1525
            kernel_key_dtype = ""
1526 1527 1528
            if op_kernel_map is not None:
                kernel_func_str = '", "'.join(op_kernel_map['func'])
                kernel_param_str = '", "'.join(op_kernel_map['param'])
1529 1530 1531 1532
                if 'data_type' in op_kernel_map and op_kernel_map['data_type']:
                    kernel_key_dtype = '", "'.join(
                        op_kernel_map['data_type']['candidates']
                    )
1533

1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
            inplace_str = ""
            view_str = ""
            if op_name[-1] == "_":
                if op_inplace_map is not None:
                    for key, value in op_inplace_map.items():
                        inplace_str += '{"' + key + '", "' + value + '"},'
                    inplace_str = inplace_str[:-1]
                if op_view_map is not None:
                    for key, value in op_view_map.items():
                        view_str += '{"' + key + '", "' + value + '"},'
                    view_str = view_str[:-1]

1546 1547 1548 1549 1550
            op_info_func_str = OP_INFO_TEMPLATE.format(
                op_name=op_class_name,
                inputs=inputs_info_str,
                attributes=attribute_info_str,
                outputs=outputs_info_str,
1551 1552 1553 1554
                infer_meta_func=infer_meta_func_str,
                infer_meta_param=infer_meta_param_str,
                kernel_func=kernel_func_str,
                kernel_param=kernel_param_str,
1555
                kernel_key_dtype=kernel_key_dtype,
1556 1557
                inplace=inplace_str,
                view=view_str,
1558
            )
1559

1560 1561 1562
            # =================================== #
            #          gen Verify func str        #
            # =================================== #
1563
            # generate op verify function: inputs_type_check_str
1564 1565 1566
            if (
                len(op_input_type_list) + len(op_mutable_attribute_name_list)
            ) == 0:
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
                inputs_type_check_str = (
                    "// Inputs num is 0, not need to check inputs type."
                )
            else:
                inputs_type_check_str = ""
            for idx in range(len(op_input_type_list)):
                input_type = op_input_type_list[idx]
                is_optional = op_input_optional_list[idx]
                is_vector = False
                if input_type.startswith("ir::VectorType<"):
                    is_vector = True
                    input_type = input_type[15:-1]
                check_str = ""
                if is_optional == "true":
                    if is_vector:
                        check_str = (
                            INPUT_OPTIONAL_VECTORTYPE_CHECK_TEMPLATE.format(
                                index=idx, standard=input_type
                            )
                        )
                    else:
                        check_str = INPUT_OPTIONAL_TYPE_CHECK_TEMPLATE.format(
                            index=idx, standard=input_type
                        )
                else:
                    if is_vector:
                        check_str = INPUT_VECTORTYPE_CHECK_TEMPLATE.format(
                            index=idx, standard=input_type
                        )
                    else:
                        check_str = INPUT_TYPE_CHECK_TEMPLATE.format(
                            index=idx, standard=input_type
                        )
                inputs_type_check_str += check_str

1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
            for idx in range(len(op_mutable_attribute_name_list)):
                mutable_attribute_type = op_mutable_attribute_type_list[idx][0]
                check_str = ""
                if mutable_attribute_type == "paddle::dialect::ScalarAttribute":
                    check_str = INPUT_TYPE_CHECK_TEMPLATE.format(
                        index=idx + len(op_input_type_list),
                        standard="paddle::dialect::DenseTensorType",
                    )
                else:
                    check_str = INPUT_VECTORTYPE_CHECK_TEMPLATE.format(
                        index=idx + len(op_input_type_list),
                        standard="paddle::dialect::DenseTensorType",
                    )
                inputs_type_check_str += check_str
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
            # generate op verify function: outputs_type_check_str
            if len(op_output_type_list) == 0:
                outputs_type_check_str = (
                    "// Outputs num is 0, not need to check outputs type."
                )
            else:
                outputs_type_check_str = ""
            for idx in range(len(op_output_type_list)):
                output_type = op_output_type_list[idx]
                is_optional = op_output_optional_list[idx]
                is_vector = False
                if output_type.startswith("ir::VectorType<"):
                    is_vector = True
                    output_type = output_type[15:-1]
                check_str = ""
                if is_optional == "true":
                    if is_vector:
                        check_str = (
                            OUTPUT_OPTIONAL_VECTORTYPE_CHECK_TEMPLATE.format(
                                index=idx, standard=output_type
                            )
                        )
                    else:
                        check_str = OUTPUT_OPTIONAL_TYPE_CHECK_TEMPLATE.format(
1640 1641 1642
                            index=idx, standard=output_type
                        )
                else:
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
                    if is_vector:
                        check_str = OUTPUT_VECTORTYPE_CHECK_TEMPLATE.format(
                            index=idx, standard=output_type
                        )
                    else:
                        check_str = OUTPUT_TYPE_CHECK_TEMPLATE.format(
                            index=idx, standard=output_type
                        )
                outputs_type_check_str += check_str
            # generate op verify function: attributes_check_str
1653
            if len(op_non_mutable_attribute_name_list) == 0:
1654 1655 1656
                attributes_check_str = (
                    "// Attributes num is 0, not need to check attributes type."
                )
1657
            else:
1658
                attributes_check_str = ""
1659 1660 1661
            for idx in range(len(op_non_mutable_attribute_name_list)):
                attribute_name = op_non_mutable_attribute_name_list[idx]
                attribute_type = op_non_mutable_attribute_type_list[idx]
1662 1663 1664 1665 1666 1667 1668
                if attribute_type.startswith("ir::ArrayAttribute<"):
                    attribute_type = attribute_type[19:-1]
                    attributes_check_str += (
                        ATTRIBUTE_VECTOR_CHECK_TEMPLATE.format(
                            attribute_name=attribute_name,
                            standard=attribute_type,
                        )
1669 1670
                    )
                else:
1671 1672
                    attributes_check_str += ATTRIBUTE_CHECK_TEMPLATE.format(
                        attribute_name=attribute_name, standard=attribute_type
1673
                    )
1674
            # generate op verify function
1675 1676 1677 1678 1679 1680 1681
            if "GradOp" in op_class_name or "Grad_Op" in op_class_name:
                op_verify_str = GRAD_OP_VERIFY_TEMPLATE.format(
                    op_name=op_class_name,
                )
            else:
                op_verify_str = OP_VERIFY_TEMPLATE.format(
                    op_name=op_class_name,
1682 1683
                    inputs_size=len(op_input_type_list)
                    + len(op_mutable_attribute_type_list),
1684 1685 1686 1687 1688
                    outputs_size=len(op_output_type_list),
                    inputs_type_check=inputs_type_check_str,
                    outputs_type_check=outputs_type_check_str,
                    attributes_check=attributes_check_str,
                )
1689

H
hong 已提交
1690 1691 1692 1693 1694 1695 1696
            op_infer_shape_str = ""
            if op_info.infer_shape_func:
                op_infer_shape_str = OP_INFER_SHAPE_TEMPLATE.format(
                    op_name=op_class_name,
                    infer_meta_func=op_info.infer_shape_func,
                )

1697 1698 1699 1700
            ops_name_list.append(op_class_name)
            ops_declare_list.append(op_declare_str)
            ops_defined_list.append(op_defined_str)
            ops_defined_list.append(op_info_func_str)
1701 1702 1703
            ops_defined_list.append(build_func_with_muta_attr_not_input)
            if len(op_mutable_attribute_name_list) > 0:
                ops_defined_list.append(build_func_with_muta_attr_is_input)
1704
            ops_defined_list.append(op_verify_str)
H
hong 已提交
1705
            ops_defined_list.append(op_infer_shape_str)
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716

    # (4) Generate head file str
    op_namespaces_prev = ""
    for name in namespaces:
        op_namespaces_prev += name + "::"
    ops_name_with_namespace_list = []
    for name in ops_name_list:
        ops_name_with_namespace_list.append(op_namespaces_prev + name)
    op_list_str = GET_OP_LIST_TEMPALTE.format(
        ", ".join(ops_name_with_namespace_list)
    )  # Add GET_OP_LIST
1717 1718 1719 1720 1721

    declare_type_id_str = ""
    for op in ops_name_with_namespace_list:
        declare_type_id_str += DECLARE_OP_TYPE_ID.format(op_name=op)

1722 1723 1724 1725 1726 1727 1728
    head_file_str = ""
    head_file_str += "".join(ops_declare_list)  # Add op class
    for name in reversed(namespaces):
        head_file_str = NAMESPACE_GARD_TEMPLATE.format(
            namespace=name, input=head_file_str
        )  # Add namespaces
    head_file_str = H_FILE_TEMPLATE.format(
1729 1730 1731
        op_declare=op_list_str,
        input=head_file_str,
        declare_type_id=declare_type_id_str,
1732 1733 1734 1735 1736 1737 1738 1739
    )  # Add head

    # (5) Generate source file str
    source_file_str = "".join(ops_defined_list)  # Add op define
    for name in reversed(namespaces):
        source_file_str = NAMESPACE_GARD_TEMPLATE.format(
            namespace=name, input=source_file_str
        )  # Add namespaces
1740 1741 1742 1743 1744

    define_type_id_str = ""
    for op in ops_name_with_namespace_list:
        define_type_id_str += DEFINE_OP_TYPE_ID.format(op_name=op)

1745
    source_file_str = CC_FILE_TEMPLATE.format(
1746 1747 1748
        h_file=op_def_h_file[:-4],
        input=source_file_str,
        define_type_id=define_type_id_str,
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
    )  # Add head

    # (5) Generate pd_op.h.tmp, pd_op.cc.tmp
    with open(op_def_h_file, 'a') as f:
        f.write(head_file_str)
    with open(op_def_cc_file, 'a') as f:
        f.write(source_file_str)


# =====================================
# Script parameter parsing
# =====================================
def ParseArguments():
    parser = argparse.ArgumentParser(
        description='Generate Dialect OP Definition Files By Yaml'
    )
    parser.add_argument('--op_yaml_files', type=str)
    parser.add_argument('--op_compat_yaml_file', type=str)
    parser.add_argument('--namespaces', type=str)
    parser.add_argument('--dialect_name', type=str)
    parser.add_argument('--op_def_h_file', type=str)
    parser.add_argument('--op_def_cc_file', type=str)
    return parser.parse_args()


# =====================================
# Main
# =====================================
if __name__ == "__main__":
    # parse arguments
    args = ParseArguments()
    op_yaml_files = args.op_yaml_files.split(",")
    op_compat_yaml_file = args.op_compat_yaml_file
    namespaces = []
    if args.namespaces is not None:
        namespaces = args.namespaces.split(",")
    dialect_name = args.dialect_name
    op_def_h_file = args.op_def_h_file
    op_def_cc_file = args.op_def_cc_file

    # auto code generate
    OpGenerator(
        op_yaml_files,
1792
        op_compat_yaml_file,
1793 1794 1795 1796 1797
        namespaces,
        dialect_name,
        op_def_h_file,
        op_def_cc_file,
    )