loop_transformer.py 27.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   Copyright (c) 2020 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 copy
16
from paddle.utils import gast
17 18 19

from collections import defaultdict
from paddle.fluid import unique_name
20 21 22
from paddle.fluid.dygraph.dygraph_to_static.static_analysis import (
    AstNodeWrapper,
)
23
from paddle.fluid.dygraph.dygraph_to_static.static_analysis import NodeVarType
24 25 26
from paddle.fluid.dygraph.dygraph_to_static.static_analysis import (
    StaticAnalysisVisitor,
)
27
from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code
28
from paddle.fluid.dygraph.dygraph_to_static.utils import get_attribute_full_name
29 30 31 32 33 34 35 36
from paddle.fluid.dygraph.dygraph_to_static.utils import (
    create_nonlocal_stmt_nodes,
    create_get_args_node,
    create_set_args_node,
)
from paddle.fluid.dygraph.dygraph_to_static.utils import (
    FunctionNameLivenessAnalysis,
)
37
from .ifelse_transformer import ARGS_NAME
38
from .base_transformer import (
39 40 41 42
    BaseTransformer,
    ForLoopTuplePreTransformer,
    ForNodeVisitor,
)
43

44 45 46 47
from paddle.fluid.dygraph.dygraph_to_static.utils import (
    GetterSetterHelper,
    create_name_str,
)
48 49 50 51 52 53

__all__ = ['LoopTransformer', 'NameVisitor']

WHILE_CONDITION_PREFIX = 'while_condition'
WHILE_BODY_PREFIX = 'while_body'

54 55 56
FOR_CONDITION_PREFIX = 'for_loop_condition'
FOR_BODY_PREFIX = 'for_loop_body'

57

58 59 60 61 62 63 64 65
def create_while_nodes(
    condition_name,
    body_name,
    loop_var_names,
    push_pop_names,
    getter_name,
    setter_name,
):
66 67 68 69 70 71 72 73 74 75 76
    """
    Returns a list of gast.Node which represents the calling of Paddle
    controlflow while_loop.

    Usually, the list just contain 1 statement such as:

    [a, b, c] = paddle.jit.dy2static.convert_while_loop(
            condition_name, body_name, [a, b, c])

    where a, b, c are in loop_var_names.

H
Huihuang Zheng 已提交
77 78
    However, if loop_var_names contains property such as foo.x, we cannot
    assign the property as output of convert_while_loop because Python
79 80 81 82 83 84 85 86 87 88 89 90
    property is a kind of read-only attribute. To handle the case, we replace
    the attributes which are output of convert_while_loop with generated
    variables, then if we know the attribute is not read-only at runtime, we
    assign the attribute. The created statements are like:

    [a, b, __attribute_variable_1] = paddle.jit.dy2static.convert_while_loop(
            condition_name, body_name, [a, b, foo.x])
    if not isinstance(getattr(type(foo), x, None), property): foo.x = __attribute_variable_1

    The number of above statements is not only 1, that's why the return type is
    a list of gast.Node.
    """
91 92 93 94 95 96
    # NOTE(liym27):
    # It's better to parse the source code into an AST node than to customize an AST node
    # including child nodes, because it is easy to mistake the ast node type when customizing the node.
    #
    # For example: loop_var_names = [a, b, foo.x], the type of `a` or `b` is gast.Name,
    # but the type of `foo.x` gast.Attribute.
97 98 99 100
    # We have to make loop_var_names and assign_loop_var_names with same order
    # set doesn't have order so we convert it to list
    loop_var_names = list(loop_var_names)
    assign_loop_var_names = []
101
    for name in loop_var_names:
102
        assign_loop_var_names.append(name)
103

104
    while_func_name = "_jst.While"
105 106 107 108 109 110 111 112 113 114 115
    while_node_str = (
        "{}({}, {}, {}, {}, return_name_ids={}, push_pop_names={})".format(
            while_func_name,
            condition_name,
            body_name,
            getter_name,
            setter_name,
            create_name_str(loop_var_names),
            create_name_str(push_pop_names),
        )
    )
116 117
    while_node = gast.parse(while_node_str).body[0]

118 119
    ret = [while_node]
    return ret
120 121 122 123 124 125 126 127


class NameVisitor(gast.NodeVisitor):
    '''
    Analysis name liveness for loop transformer
    '''

    def __init__(self, root_node):
128
        # Set of gast.Name or gast.Attribute for variables
129
        self.current_seen_vars = set()
130

131 132 133
        # List of gast.While/gast.For nodes
        self.current_loop = []

134 135 136 137
        # List of nodes that have scope of variables.
        self.nodes_with_scope = []
        self.blacklist_names = {"False", "True", "None"}

138 139
        # Mapping from gast.While/gast.For to variable nodes
        self.before_loop_body_vars = defaultdict(set)
140 141
        # NOTE: Use ordered list as dict value
        self.in_loop_vars = defaultdict(list)
142

143 144 145 146 147 148
        # Mapping from gast.While/gast.For to variable nodes which is condition
        # of loop or being modified during the loop
        self.write_in_loop = defaultdict(set)
        self.condition_vars = defaultdict(set)
        self.in_condition = False

149 150 151
        # Some names are types, we shouldn't record them as loop var names.
        self.type_vars = set()

152
        self.static_analysis_visitor = StaticAnalysisVisitor(root_node)
153 154
        self.node_to_wrapper_map = (
            self.static_analysis_visitor.get_node_to_wrapper_map()
155 156
        )

157 158 159
        self.visit(root_node)

    def get_loop_var_names(self, node):
160
        assert isinstance(
161 162
            node, (gast.While, gast.For)
        ), "Input node is not gast loop node"
163 164
        loop_var_names = set()
        create_var_names = set()
H
Huihuang Zheng 已提交
165
        read_context = {type(gast.Load()), type(gast.AugLoad())}
166

167 168 169 170 171 172
        in_loop_vars_list = self.in_loop_vars[node]

        # get dict `var_name_to_ctxs`
        var_name_to_ctxs = defaultdict(list)
        for var_node in in_loop_vars_list:
            var_name_to_ctxs[self._var_node_to_name(var_node)].append(
173 174
                var_node.ctx
            )
175 176

        in_loop_vars = set(in_loop_vars_list)
177
        in_loop_vars = self._remove_unnecessary_vars(in_loop_vars, node)
178
        in_loop_name_strs = self._var_nodes_to_names(in_loop_vars)
179

180
        before_loop_body_vars = self.before_loop_body_vars[node]
181
        before_loop_body_vars = self._remove_unnecessary_vars(
182 183
            before_loop_body_vars, node
        )
184
        before_loop_name_strs = self._var_nodes_to_names(before_loop_body_vars)
185

186 187 188
        after_loop_vars = (
            self.current_seen_vars - before_loop_body_vars - in_loop_vars
        )
189
        after_loop_vars = self._remove_unnecessary_vars(after_loop_vars, node)
190 191 192
        after_loop_name_strs = self._var_nodes_to_names(
            after_loop_vars, read_context
        )
193 194
        condition_vars = self.condition_vars[node]
        condition_names = self._var_nodes_to_names(condition_vars)
195

196 197 198 199 200 201 202
        write_vars = self.write_in_loop[node]
        write_names = self._var_nodes_to_names(write_vars)

        name_to_type = {}
        for var in in_loop_vars:
            wrapper = self.node_to_wrapper_map[var]
            name_to_type[self._var_node_to_name(var)] = wrapper.node_var_type
203 204
        for name in in_loop_name_strs:
            if name in before_loop_name_strs:
205 206 207 208 209
                # If a variable is used in loop and created before loop

                # If this var is a basic variable and read-only and not
                # condition var, it may not be loop_var else it should
                # be in loop_var as input
210
                if (name not in condition_names) and (name not in write_names):
211
                    continue
212
                loop_var_names.add(name)
213

214 215 216
            elif name in after_loop_name_strs:
                # If a variable is created in the while loop and read after
                # loop, it should be in loop_var and we should create it
217 218 219 220

                # because name in after_loop_name must be initialized in loop
                # So it is write-only, we don't have to filter read-only basic
                # vars out
221 222
                loop_var_names.add(name)
                create_var_names.add(name)
223 224 225 226 227 228 229 230 231 232 233 234 235
            else:
                # If a variable is used and created in loop, but used before created,
                # it should be in loop_var and we should create it.

                # For example, `var_a` should be in loop_var and we should create it.
                #
                #   res = 0
                #   for i, x in enumerate(x_array):
                #       if i > 2:
                #           x = func1(var_a)
                #       var_a = func2(x)
                #

236 237 238 239 240
                is_created = False
                for ctx in var_name_to_ctxs[name]:
                    if isinstance(ctx, gast.Store):
                        is_created = True

241 242 243 244
                if (
                    isinstance(var_name_to_ctxs[name][0], gast.Load)
                    and is_created
                ):
245 246
                    loop_var_names.add(name)
                    create_var_names.add(name)
247

248 249 250
        return loop_var_names, create_var_names

    def visit_Name(self, node):
251 252 253
        if self._is_call_func_name_node(node):
            self.generic_visit(node)
            return
254
        if node.id in self.blacklist_names:
255 256
            self.generic_visit(node)
            return
257

258
        self.current_seen_vars.add(node)
259
        write_context = {
260 261
            type(gast.Store()),
            type(gast.AugStore()),
262
            type(gast.Del()),
263
        }
264

265
        for loop_node in self.current_loop:
266
            self.in_loop_vars[loop_node].append(node)
267 268
            if type(node.ctx) in write_context:
                self.write_in_loop[loop_node].add(node)
269 270
        if self.in_condition:
            self.condition_vars[loop_node].add(node)
271 272
        self.generic_visit(node)

273 274 275
    def visit_FunctionDef(self, node):
        self.nodes_with_scope.append(node)
        self.blacklist_names.add(node.name)
276

277 278 279 280 281 282 283 284 285 286
        # The variables in the function are not visible to the outside scope.
        before_func_seen_vars = copy.copy(self.current_seen_vars)

        self.generic_visit(node)
        self.nodes_with_scope.pop()
        # After exiting the scope of the node, variables in this scope
        # should be removed from self.current_seen_vars.
        if self.nodes_with_scope:
            self.current_seen_vars = before_func_seen_vars

287 288 289 290 291 292 293 294 295 296
    def visit(self, node):
        method = 'visit_' + node.__class__.__name__
        visitor = getattr(self, method, self.generic_visit)
        ret = visitor(node)
        return ret

    def visit_Attribute(self, node):
        if self._is_call_func_name_node(node):
            return
        attr_full_name = get_attribute_full_name(node)
297 298 299 300 301 302 303 304 305 306
        # Class variables are not allowed to appear in the arguments list
        # of defined function under class methods in Python.
        """
        def class_func(self):
            def while_loop_body(self.x, y) # `self.x` is illegal.
        """
        # TODO: If do change the variable with `self.var`, need a better
        # way to deal with this case.
        if attr_full_name.startswith("self."):
            return
307
        self.current_seen_vars.add(node)
308

309
        for loop_node in self.current_loop:
310
            self.in_loop_vars[loop_node].append(node)
311

312 313 314
        # sub-nodes are visited during get_attribute_full_name and we shouldn't
        # visit again

315 316
    def visit_For(self, node):
        self.current_loop.append(node)
317
        self.in_condition = True
318
        self.visit(node.target)
319 320
        self.visit(node.iter)
        self.in_condition = False
321
        self.before_loop_body_vars[node] = copy.copy(self.current_seen_vars)
322 323 324 325 326
        self.generic_visit(node)
        self.current_loop.pop()

    def visit_While(self, node):
        self.current_loop.append(node)
327
        self.in_condition = True
328
        self.visit(node.test)
329
        self.in_condition = False
330
        self.before_loop_body_vars[node] = copy.copy(self.current_seen_vars)
331 332 333
        self.generic_visit(node)
        self.current_loop.pop()

334 335 336 337 338 339 340
    def visit_Call(self, node):
        # Store type var names such as "isinstance(x, some_type_names)" and
        # Remove them later
        if isinstance(node.func, gast.Name) and node.func.id == 'isinstance':
            type_node = node.args[1]
            if isinstance(type_node, gast.Tuple):
                for element in type_node.elts:
341
                    self.type_vars.add(ast_to_source_code(element).strip())
342
            else:
343
                self.type_vars.add(ast_to_source_code(type_node).strip())
344 345
        self.generic_visit(node)

346 347 348 349
    def _var_nodes_to_names(self, node_set, ctx_filter_set=None):
        ret = set()
        for node in node_set:
            if ctx_filter_set is None or type(node.ctx) in ctx_filter_set:
350
                ret.add(self._var_node_to_name(node))
351 352
        return ret

353 354 355 356 357 358 359 360
    def _var_node_to_name(self, node):
        if isinstance(node, gast.Name):
            return node.id
        elif isinstance(node, gast.Attribute):
            return get_attribute_full_name(node)

    def _node_var_type_is_basic(self, node_var_type):
        basic_types = {
361 362 363 364
            NodeVarType.BOOLEAN,
            NodeVarType.INT,
            NodeVarType.FLOAT,
            NodeVarType.STRING,
365 366 367 368 369 370
        }
        for t in node_var_type:
            if t in basic_types:
                return True
        return False

371
    def _is_call_func_name_node(self, node):
372
        parent_node = self._get_parent_node(node)
373 374
        if isinstance(parent_node, gast.Call) and parent_node.func == node:
            return True
375 376
        return False

377 378 379
    def _is_global_or_nonlocal(self, node):
        return False

380 381 382 383 384 385 386 387 388
    def _is_ancestor_node(self, ancestor_node, node):
        parent_node = self._get_parent_node(node)

        while parent_node is not None:
            if parent_node == ancestor_node:
                return True
            parent_node = self._get_parent_node(parent_node)
        return False

389 390 391
    def _get_parent_node(self, node):
        wrapper_node = self.node_to_wrapper_map.get(node)
        if wrapper_node:
392 393 394
            if wrapper_node.parent:
                parent_node = wrapper_node.parent.node
                return parent_node
395 396
        return None

397
    def _remove_unnecessary_vars(self, loop_vars, loop_node):
398
        """
399 400 401
        Remove unnecessary vars from before_loop_vars, after_loop_vars or in_loop_vars about loop_node.
            1. Remove target vars of gast.For from before_loop_vars or after_loop_vars.
            2. Remove vars only in gast.comprehension.
402
            3. Remove vars that are type names, for example: "isinstance(x, var_type_name)"
403
        :param loop_vars: before_loop_vars, after_loop_vars or in_loop_vars of loop_node.
404 405 406
        :param loop_node: Current loop node.
        """

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
        def filter_name_nodes_from(root_node, target_var_names):
            """
            Filter children with gast.Name type from node.(inclusivly)
            """
            name_nodes = set()
            if isinstance(root_node, gast.Name):
                if node.id in target_var_names:
                    name_nodes.add(root_node)
            for child_node in gast.walk(root_node):
                if isinstance(child_node, gast.Name):
                    if child_node.id in target_var_names:
                        name_nodes.add(child_node)

            return name_nodes

422 423 424 425
        vars_of_list_generator = set()
        target_vars_of_for_node = set()

        for name_node in loop_vars:
426 427 428 429 430
            if not isinstance(name_node, gast.Name):
                continue

            parent_node = self._get_parent_node(name_node)

431 432 433 434
            # NOTE: gast.For.target or gast.comprehension.target can be gast.Tuple.
            #  For examples:
            #   1) `for i, j in enumerate(x)` has two target vars: i and j
            #   2) `[x for x,y in array]` has two target vars: x and y
435 436 437
            if isinstance(parent_node, gast.Tuple):
                parent_node = self._get_parent_node(parent_node)

438 439 440 441 442 443 444
            # 1. Get vars only in gast.comprehension.
            # For examples:
            #  1) [x for x,y in array] -> x, x, y
            #  2) [f(x) for x in array] -> x
            #  3) [func(x, y) for x in array] -> x, x
            if isinstance(parent_node, gast.comprehension):
                # 1.1 target vars in list/set comprehensions
445 446 447 448 449 450
                target_node = parent_node.target
                if isinstance(target_node, gast.Tuple):
                    target_vars = target_node.elts
                else:
                    target_vars = [target_node]

451
                vars_of_list_generator = vars_of_list_generator | set(
452 453
                    target_vars
                )
454 455 456

                # 1.2 vars from target vars used in elt_node
                target_var_names = {var.id for var in target_vars}
457 458 459 460 461 462 463 464 465
                comp_node = self._get_parent_node(parent_node)
                elt_nodes = []
                if isinstance(comp_node, gast.ListComp):
                    elt_nodes.append(comp_node.elt)
                elif isinstance(comp_node, gast.DictComp):
                    elt_nodes.extend([comp_node.key, comp_node.value])

                for node in elt_nodes:
                    vars_of_list_generator |= filter_name_nodes_from(
466 467
                        node, target_var_names
                    )
468

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
            # 2. Get target vars or vars from target vars used in for-loop but the for-loop is
            #   1) not the "loop_node" itself
            #   2) not the ancestor of the "loop_node"
            #
            # For examples:
            #   for k in range(x):   # if it's this "loop_node", i or j both should be target vars.
            #      # do something
            #
            #   for i in range(a):   # if it's this "loop_node", k or j should be in target vars but i should not.
            #     for j in range(a): # if it's this "loop_node", k should be in target_vars but i or j should not.
            #       x = i+j
            elif isinstance(parent_node, gast.For):
                if parent_node is loop_node:
                    continue
                if self._is_ancestor_node(parent_node, loop_node):
                    continue
485 486 487 488 489 490
                # 2.1 target vars in gast.For node.
                target_node = parent_node.target
                if isinstance(target_node, gast.Tuple):
                    target_vars = target_node.elts
                else:
                    target_vars = [target_node]
491

492
                target_vars_of_for_node = target_vars_of_for_node | set(
493 494
                    target_vars
                )
495

496 497 498
        # 2.2 vars from target vars used in for-loop
        target_vars_name_strs = {var.id for var in target_vars_of_for_node}
        for var in loop_vars:
499 500
            if not isinstance(var, gast.Name):
                continue
501 502 503 504
            if (
                var.id in target_vars_name_strs
                and var not in self.condition_vars[loop_node]
            ):
505
                target_vars_of_for_node.add(var)
506

507
        removed_vars = target_vars_of_for_node | vars_of_list_generator
508 509 510

        # 3. Remove var type names which are stored in self.type_vars
        for var in loop_vars:
511
            if ast_to_source_code(var).strip() in self.type_vars:
512 513
                removed_vars.add(var)

514
        return loop_vars - removed_vars
515

516

517
class LoopTransformer(BaseTransformer):
518 519 520 521 522 523 524
    """
    This class transforms python while/for statement into Static Graph Ast
    """

    def __init__(self, wrapper_root):
        assert isinstance(
            wrapper_root, AstNodeWrapper
525
        ), "Input non-AstNodeWrapper node for the initialization of LoopTransformer."
526 527
        self.wrapper_root = wrapper_root
        self.root = wrapper_root.node
528
        FunctionNameLivenessAnalysis(self.root)
529 530

    def transform(self):
531
        ForLoopTuplePreTransformer(self.wrapper_root).transform()
532 533
        self.visit(self.root)

534 535 536 537 538 539
    def visit_While(self, node):
        self.generic_visit(node)
        new_stmts = self.get_while_stmt_nodes(node)
        return new_stmts

    def visit_For(self, node):
540
        self.generic_visit(node)
541 542
        new_stmts = self.get_for_stmt_nodes(node)
        return new_stmts
543 544 545 546 547 548 549 550 551

    def replace_stmt_list(self, body_list):
        if not isinstance(body_list, list):
            return

        i = 0
        while i < len(body_list):
            if isinstance(body_list[i], gast.While):
                new_stmts = self.get_while_stmt_nodes(body_list[i])
552
                body_list[i : i + 1] = new_stmts
553 554
                i += len(new_stmts)
            elif isinstance(body_list[i], gast.For):
555
                new_stmts = self.get_for_stmt_nodes(body_list[i])
556
                body_list[i : i + 1] = new_stmts
557
                i += len(new_stmts)
558 559 560
            else:
                i += 1

561 562 563
    def get_for_stmt_nodes(self, node):
        # TODO: consider for - else in python

564 565
        # 1. get key statements for different cases
        # NOTE 1: three key statements:
566 567 568 569
        #   1). init_stmts: list[node], prepare nodes of for loop, may not only one
        #   2). cond_stmt: node, condition node to judge whether continue loop
        #   3). body_stmts: list[node], updated loop body, sometimes we should change
        #       the original statement in body, not just append new statement
570 571 572 573 574 575
        #
        # NOTE 2: The following `for` statements will be transformed to `while` statements:
        #   1). for x in range(*)
        #   2). for x in iter_var
        #   3). for i, x in enumerate(*)

576
        current_for_node_parser = ForNodeVisitor(node)
577 578
        stmts_tuple = current_for_node_parser.parse()
        if stmts_tuple is None:
579
            return [node]
580
        init_stmts, cond_stmt, body_stmts = stmts_tuple
581
        # 2. get original loop vars
582 583 584 585
        loop_var_names, create_var_names = (
            node.pd_scope.modified_vars(),
            node.pd_scope.created_vars(),
        )
586
        push_pop_names = list(node.pd_scope.variadic_length_vars())
587
        # TODO: Remove the bunch of code?  We have the unique format `for A in B:`
588 589 590 591
        # NOTE: in 'for x in var' or 'for i, x in enumerate(var)' cases,
        # we need append new loop var & remove useless loop var
        #   1. for x in var -> x is no need
        #   2. for i, x in enumerate(var) -> x is no need
592
        if current_for_node_parser.is_for_iter():
593 594 595
            iter_var_name = current_for_node_parser.iter_var_name
            iter_idx_name = current_for_node_parser.iter_idx_name
            loop_var_names.add(iter_idx_name)
596 597
            if current_for_node_parser.enum_idx_name is not None:
                loop_var_names.add(current_for_node_parser.enum_idx_name)
598

599
        # 3. prepare result statement list
600 601 602 603 604 605 606
        new_stmts = []
        # Python can create variable in loop and use it out of loop, E.g.
        #
        # for x in range(10):
        #     y += x
        # print(x) # x = 10
        #
607 608
        # We don't need to create static variable for them, because
        # we do this in CreateUndefinedVarTransformer
609 610 611 612 613 614 615 616

        # create non-local statement for body and cond.
        nonlocal_names = list(loop_var_names | create_var_names)
        nonlocal_names.sort()
        # TODO(dev): Need a better way to deal this.
        if ARGS_NAME in nonlocal_names:
            nonlocal_names.remove(ARGS_NAME)

617
        nonlocal_stmt_node = create_nonlocal_stmt_nodes(nonlocal_names)
618

619
        # 4. append init statements
620
        new_stmts.extend(init_stmts)
621

622
        # 5. create & append condition function node
623 624
        condition_func_node = gast.FunctionDef(
            name=unique_name.generate(FOR_CONDITION_PREFIX),
625 626 627 628 629 630 631 632 633
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
634
            body=nonlocal_stmt_node + [gast.Return(value=cond_stmt)],
635 636
            decorator_list=[],
            returns=None,
637 638
            type_comment=None,
        )
639 640
        new_stmts.append(condition_func_node)

641
        # 6. create & append loop body function node
642
        # append return values for loop body
643 644
        body_func_node = gast.FunctionDef(
            name=unique_name.generate(FOR_BODY_PREFIX),
645 646 647 648 649 650 651 652 653
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
654
            body=nonlocal_stmt_node + body_stmts,
655 656
            decorator_list=[],
            returns=None,
657 658
            type_comment=None,
        )
659 660
        new_stmts.append(body_func_node)

661 662 663
        helper = GetterSetterHelper(None, None, nonlocal_names, push_pop_names)
        get_args_node = create_get_args_node(helper.union())
        set_args_node = create_set_args_node(helper.union())
664
        # 7. create & append while loop node
665 666 667 668 669 670 671 672
        while_loop_nodes = create_while_nodes(
            condition_func_node.name,
            body_func_node.name,
            nonlocal_names,
            push_pop_names,
            get_args_node.name,
            set_args_node.name,
        )
673
        new_stmts.extend([get_args_node, set_args_node])
674
        new_stmts.extend(while_loop_nodes)
675 676 677

        return new_stmts

678
    def get_while_stmt_nodes(self, node):
679 680 681 682
        loop_var_names, create_var_names = (
            node.pd_scope.modified_vars(),
            node.pd_scope.created_vars(),
        )
683
        push_pop_names = list(node.pd_scope.variadic_length_vars())
684 685
        new_stmts = []

686 687 688 689 690 691 692
        # create non-local statement for body and cond.
        nonlocal_names = list(loop_var_names | create_var_names)
        nonlocal_names.sort()
        # TODO(dev): Need a better way to deal this.
        if ARGS_NAME in nonlocal_names:
            nonlocal_names.remove(ARGS_NAME)

693
        nonlocal_stmt_node = create_nonlocal_stmt_nodes(nonlocal_names)
694

695 696 697 698 699 700 701
        # Python can create variable in loop and use it out of loop, E.g.
        #
        # while x < 10:
        #     x += 1
        #     y = x
        # z = y
        #
702 703
        # We don't need to create static variable for those variables, because
        # we do this in CreateUndefinedVarTransformer
704 705 706

        condition_func_node = gast.FunctionDef(
            name=unique_name.generate(WHILE_CONDITION_PREFIX),
707 708 709 710 711 712 713 714 715
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
716
            body=nonlocal_stmt_node + [gast.Return(value=node.test)],
717 718
            decorator_list=[],
            returns=None,
719 720
            type_comment=None,
        )
721

722 723 724 725 726
        new_stmts.append(condition_func_node)

        new_body = node.body
        body_func_node = gast.FunctionDef(
            name=unique_name.generate(WHILE_BODY_PREFIX),
727 728 729 730 731 732 733 734 735
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
736
            body=nonlocal_stmt_node + new_body,
737 738
            decorator_list=[],
            returns=None,
739 740
            type_comment=None,
        )
741
        new_stmts.append(body_func_node)
742 743 744 745

        helper = GetterSetterHelper(None, None, nonlocal_names, push_pop_names)
        get_args_node = create_get_args_node(helper.union())
        set_args_node = create_set_args_node(helper.union())
746

747 748 749 750 751 752 753 754
        while_loop_nodes = create_while_nodes(
            condition_func_node.name,
            body_func_node.name,
            nonlocal_names,
            push_pop_names,
            get_args_node.name,
            set_args_node.name,
        )
755
        new_stmts.extend([get_args_node, set_args_node])
756
        new_stmts.extend(while_loop_nodes)
757
        return new_stmts