loop_transformer.py 27.0 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 23
from .static_analysis import AstNodeWrapper, NodeVarType, StaticAnalysisVisitor
from .utils import (
    ast_to_source_code,
    get_attribute_full_name,
24 25 26 27
    create_nonlocal_stmt_nodes,
    create_get_args_node,
    create_set_args_node,
    FunctionNameLivenessAnalysis,
28 29
    GetterSetterHelper,
    create_name_str,
30
)
31
from .ifelse_transformer import ARGS_NAME
32
from .base_transformer import (
33 34 35 36
    BaseTransformer,
    ForLoopTuplePreTransformer,
    ForNodeVisitor,
)
37

38

39
__all__ = []
40 41 42 43

WHILE_CONDITION_PREFIX = 'while_condition'
WHILE_BODY_PREFIX = 'while_body'

44 45 46
FOR_CONDITION_PREFIX = 'for_loop_condition'
FOR_BODY_PREFIX = 'for_loop_body'

47

48 49 50 51 52 53 54 55
def create_while_nodes(
    condition_name,
    body_name,
    loop_var_names,
    push_pop_names,
    getter_name,
    setter_name,
):
56 57 58 59 60 61 62 63 64 65 66
    """
    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 已提交
67 68
    However, if loop_var_names contains property such as foo.x, we cannot
    assign the property as output of convert_while_loop because Python
69 70 71 72 73 74 75 76 77 78 79 80
    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.
    """
81 82 83 84 85 86
    # 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.
87 88 89 90
    # 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 = []
91
    for name in loop_var_names:
92
        assign_loop_var_names.append(name)
93

94
    while_func_name = "_jst.While"
95 96 97 98 99 100 101 102 103 104 105
    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),
        )
    )
106 107
    while_node = gast.parse(while_node_str).body[0]

108 109
    ret = [while_node]
    return ret
110 111 112 113 114 115 116 117


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

    def __init__(self, root_node):
118
        # Set of gast.Name or gast.Attribute for variables
119
        self.current_seen_vars = set()
120

121 122 123
        # List of gast.While/gast.For nodes
        self.current_loop = []

124 125 126 127
        # List of nodes that have scope of variables.
        self.nodes_with_scope = []
        self.blacklist_names = {"False", "True", "None"}

128 129
        # Mapping from gast.While/gast.For to variable nodes
        self.before_loop_body_vars = defaultdict(set)
130 131
        # NOTE: Use ordered list as dict value
        self.in_loop_vars = defaultdict(list)
132

133 134 135 136 137 138
        # 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

139 140 141
        # Some names are types, we shouldn't record them as loop var names.
        self.type_vars = set()

142
        self.static_analysis_visitor = StaticAnalysisVisitor(root_node)
143 144
        self.node_to_wrapper_map = (
            self.static_analysis_visitor.get_node_to_wrapper_map()
145 146
        )

147 148 149
        self.visit(root_node)

    def get_loop_var_names(self, node):
150
        assert isinstance(
151 152
            node, (gast.While, gast.For)
        ), "Input node is not gast loop node"
153 154
        loop_var_names = set()
        create_var_names = set()
H
Huihuang Zheng 已提交
155
        read_context = {type(gast.Load()), type(gast.AugLoad())}
156

157 158 159 160 161 162
        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(
163 164
                var_node.ctx
            )
165 166

        in_loop_vars = set(in_loop_vars_list)
167
        in_loop_vars = self._remove_unnecessary_vars(in_loop_vars, node)
168
        in_loop_name_strs = self._var_nodes_to_names(in_loop_vars)
169

170
        before_loop_body_vars = self.before_loop_body_vars[node]
171
        before_loop_body_vars = self._remove_unnecessary_vars(
172 173
            before_loop_body_vars, node
        )
174
        before_loop_name_strs = self._var_nodes_to_names(before_loop_body_vars)
175

176 177 178
        after_loop_vars = (
            self.current_seen_vars - before_loop_body_vars - in_loop_vars
        )
179
        after_loop_vars = self._remove_unnecessary_vars(after_loop_vars, node)
180 181 182
        after_loop_name_strs = self._var_nodes_to_names(
            after_loop_vars, read_context
        )
183 184
        condition_vars = self.condition_vars[node]
        condition_names = self._var_nodes_to_names(condition_vars)
185

186 187 188 189 190 191 192
        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
193 194
        for name in in_loop_name_strs:
            if name in before_loop_name_strs:
195 196 197 198 199
                # 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
200
                if (name not in condition_names) and (name not in write_names):
201
                    continue
202
                loop_var_names.add(name)
203

204 205 206
            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
207 208 209 210

                # 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
211 212
                loop_var_names.add(name)
                create_var_names.add(name)
213 214 215 216 217 218 219 220 221 222 223 224 225
            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)
                #

226 227 228 229 230
                is_created = False
                for ctx in var_name_to_ctxs[name]:
                    if isinstance(ctx, gast.Store):
                        is_created = True

231 232 233 234
                if (
                    isinstance(var_name_to_ctxs[name][0], gast.Load)
                    and is_created
                ):
235 236
                    loop_var_names.add(name)
                    create_var_names.add(name)
237

238 239 240
        return loop_var_names, create_var_names

    def visit_Name(self, node):
241 242 243
        if self._is_call_func_name_node(node):
            self.generic_visit(node)
            return
244
        if node.id in self.blacklist_names:
245 246
            self.generic_visit(node)
            return
247

248
        self.current_seen_vars.add(node)
249
        write_context = {
250 251
            type(gast.Store()),
            type(gast.AugStore()),
252
            type(gast.Del()),
253
        }
254

255
        for loop_node in self.current_loop:
256
            self.in_loop_vars[loop_node].append(node)
257 258
            if type(node.ctx) in write_context:
                self.write_in_loop[loop_node].add(node)
259 260
        if self.in_condition:
            self.condition_vars[loop_node].add(node)
261 262
        self.generic_visit(node)

263 264 265
    def visit_FunctionDef(self, node):
        self.nodes_with_scope.append(node)
        self.blacklist_names.add(node.name)
266

267 268 269 270 271 272 273 274 275 276
        # 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

277 278 279 280 281 282 283 284 285 286
    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)
287 288 289 290 291 292 293 294 295 296
        # 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
297
        self.current_seen_vars.add(node)
298

299
        for loop_node in self.current_loop:
300
            self.in_loop_vars[loop_node].append(node)
301

302 303 304
        # sub-nodes are visited during get_attribute_full_name and we shouldn't
        # visit again

305 306
    def visit_For(self, node):
        self.current_loop.append(node)
307
        self.in_condition = True
308
        self.visit(node.target)
309 310
        self.visit(node.iter)
        self.in_condition = False
311
        self.before_loop_body_vars[node] = copy.copy(self.current_seen_vars)
312 313 314 315 316
        self.generic_visit(node)
        self.current_loop.pop()

    def visit_While(self, node):
        self.current_loop.append(node)
317
        self.in_condition = True
318
        self.visit(node.test)
319
        self.in_condition = False
320
        self.before_loop_body_vars[node] = copy.copy(self.current_seen_vars)
321 322 323
        self.generic_visit(node)
        self.current_loop.pop()

324 325 326 327 328 329 330
    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:
331
                    self.type_vars.add(ast_to_source_code(element).strip())
332
            else:
333
                self.type_vars.add(ast_to_source_code(type_node).strip())
334 335
        self.generic_visit(node)

336 337 338 339
    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:
340
                ret.add(self._var_node_to_name(node))
341 342
        return ret

343 344 345 346 347 348 349 350
    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 = {
351 352 353 354
            NodeVarType.BOOLEAN,
            NodeVarType.INT,
            NodeVarType.FLOAT,
            NodeVarType.STRING,
355 356 357 358 359 360
        }
        for t in node_var_type:
            if t in basic_types:
                return True
        return False

361
    def _is_call_func_name_node(self, node):
362
        parent_node = self._get_parent_node(node)
363 364
        if isinstance(parent_node, gast.Call) and parent_node.func == node:
            return True
365 366
        return False

367 368 369
    def _is_global_or_nonlocal(self, node):
        return False

370 371 372 373 374 375 376 377 378
    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

379 380 381
    def _get_parent_node(self, node):
        wrapper_node = self.node_to_wrapper_map.get(node)
        if wrapper_node:
382 383 384
            if wrapper_node.parent:
                parent_node = wrapper_node.parent.node
                return parent_node
385 386
        return None

387
    def _remove_unnecessary_vars(self, loop_vars, loop_node):
388
        """
389 390 391
        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.
392
            3. Remove vars that are type names, for example: "isinstance(x, var_type_name)"
393
        :param loop_vars: before_loop_vars, after_loop_vars or in_loop_vars of loop_node.
394 395 396
        :param loop_node: Current loop node.
        """

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
        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

412 413 414 415
        vars_of_list_generator = set()
        target_vars_of_for_node = set()

        for name_node in loop_vars:
416 417 418 419 420
            if not isinstance(name_node, gast.Name):
                continue

            parent_node = self._get_parent_node(name_node)

421 422 423 424
            # 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
425 426 427
            if isinstance(parent_node, gast.Tuple):
                parent_node = self._get_parent_node(parent_node)

428 429 430 431 432 433 434
            # 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
435 436 437 438 439 440
                target_node = parent_node.target
                if isinstance(target_node, gast.Tuple):
                    target_vars = target_node.elts
                else:
                    target_vars = [target_node]

441
                vars_of_list_generator = vars_of_list_generator | set(
442 443
                    target_vars
                )
444 445 446

                # 1.2 vars from target vars used in elt_node
                target_var_names = {var.id for var in target_vars}
447 448 449 450 451 452 453 454 455
                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(
456 457
                        node, target_var_names
                    )
458

459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
            # 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
475 476 477 478 479 480
                # 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]
481

482
                target_vars_of_for_node = target_vars_of_for_node | set(
483 484
                    target_vars
                )
485

486 487 488
        # 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:
489 490
            if not isinstance(var, gast.Name):
                continue
491 492 493 494
            if (
                var.id in target_vars_name_strs
                and var not in self.condition_vars[loop_node]
            ):
495
                target_vars_of_for_node.add(var)
496

497
        removed_vars = target_vars_of_for_node | vars_of_list_generator
498 499 500

        # 3. Remove var type names which are stored in self.type_vars
        for var in loop_vars:
501
            if ast_to_source_code(var).strip() in self.type_vars:
502 503
                removed_vars.add(var)

504
        return loop_vars - removed_vars
505

506

507
class LoopTransformer(BaseTransformer):
508 509 510 511 512 513 514
    """
    This class transforms python while/for statement into Static Graph Ast
    """

    def __init__(self, wrapper_root):
        assert isinstance(
            wrapper_root, AstNodeWrapper
515
        ), "Input non-AstNodeWrapper node for the initialization of LoopTransformer."
516 517
        self.wrapper_root = wrapper_root
        self.root = wrapper_root.node
518
        FunctionNameLivenessAnalysis(self.root)
519 520

    def transform(self):
521
        ForLoopTuplePreTransformer(self.wrapper_root).transform()
522 523
        self.visit(self.root)

524 525 526 527 528 529
    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):
530
        self.generic_visit(node)
531 532
        new_stmts = self.get_for_stmt_nodes(node)
        return new_stmts
533 534 535 536 537 538 539 540 541

    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])
542
                body_list[i : i + 1] = new_stmts
543 544
                i += len(new_stmts)
            elif isinstance(body_list[i], gast.For):
545
                new_stmts = self.get_for_stmt_nodes(body_list[i])
546
                body_list[i : i + 1] = new_stmts
547
                i += len(new_stmts)
548 549 550
            else:
                i += 1

551 552 553
    def get_for_stmt_nodes(self, node):
        # TODO: consider for - else in python

554 555
        # 1. get key statements for different cases
        # NOTE 1: three key statements:
556 557 558 559
        #   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
560 561 562 563 564 565
        #
        # 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(*)

566
        current_for_node_parser = ForNodeVisitor(node)
567 568
        stmts_tuple = current_for_node_parser.parse()
        if stmts_tuple is None:
569
            return [node]
570
        init_stmts, cond_stmt, body_stmts = stmts_tuple
571
        # 2. get original loop vars
572 573 574 575
        loop_var_names, create_var_names = (
            node.pd_scope.modified_vars(),
            node.pd_scope.created_vars(),
        )
576
        push_pop_names = list(node.pd_scope.variadic_length_vars())
577
        # TODO: Remove the bunch of code?  We have the unique format `for A in B:`
578 579 580 581
        # 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
582
        if current_for_node_parser.is_for_iter():
583 584 585
            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)
586 587
            if current_for_node_parser.enum_idx_name is not None:
                loop_var_names.add(current_for_node_parser.enum_idx_name)
588

589
        # 3. prepare result statement list
590 591 592 593 594 595 596
        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
        #
597 598
        # We don't need to create static variable for them, because
        # we do this in CreateUndefinedVarTransformer
599 600 601 602 603 604 605 606

        # 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)

607
        nonlocal_stmt_node = create_nonlocal_stmt_nodes(nonlocal_names)
608

609
        # 4. append init statements
610
        new_stmts.extend(init_stmts)
611

612
        # 5. create & append condition function node
613 614
        condition_func_node = gast.FunctionDef(
            name=unique_name.generate(FOR_CONDITION_PREFIX),
615 616 617 618 619 620 621 622 623
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
624
            body=nonlocal_stmt_node + [gast.Return(value=cond_stmt)],
625 626
            decorator_list=[],
            returns=None,
627 628
            type_comment=None,
        )
629 630
        new_stmts.append(condition_func_node)

631
        # 6. create & append loop body function node
632
        # append return values for loop body
633 634
        body_func_node = gast.FunctionDef(
            name=unique_name.generate(FOR_BODY_PREFIX),
635 636 637 638 639 640 641 642 643
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
644
            body=nonlocal_stmt_node + body_stmts,
645 646
            decorator_list=[],
            returns=None,
647 648
            type_comment=None,
        )
649 650
        new_stmts.append(body_func_node)

651 652 653
        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())
654
        # 7. create & append while loop node
655 656 657 658 659 660 661 662
        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,
        )
663
        new_stmts.extend([get_args_node, set_args_node])
664
        new_stmts.extend(while_loop_nodes)
665 666 667

        return new_stmts

668
    def get_while_stmt_nodes(self, node):
669 670 671 672
        loop_var_names, create_var_names = (
            node.pd_scope.modified_vars(),
            node.pd_scope.created_vars(),
        )
673
        push_pop_names = list(node.pd_scope.variadic_length_vars())
674 675
        new_stmts = []

676 677 678 679 680 681 682
        # 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)

683
        nonlocal_stmt_node = create_nonlocal_stmt_nodes(nonlocal_names)
684

685 686 687 688 689 690 691
        # Python can create variable in loop and use it out of loop, E.g.
        #
        # while x < 10:
        #     x += 1
        #     y = x
        # z = y
        #
692 693
        # We don't need to create static variable for those variables, because
        # we do this in CreateUndefinedVarTransformer
694 695 696

        condition_func_node = gast.FunctionDef(
            name=unique_name.generate(WHILE_CONDITION_PREFIX),
697 698 699 700 701 702 703 704 705
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
706
            body=nonlocal_stmt_node + [gast.Return(value=node.test)],
707 708
            decorator_list=[],
            returns=None,
709 710
            type_comment=None,
        )
711

712 713 714 715 716
        new_stmts.append(condition_func_node)

        new_body = node.body
        body_func_node = gast.FunctionDef(
            name=unique_name.generate(WHILE_BODY_PREFIX),
717 718 719 720 721 722 723 724 725
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
726
            body=nonlocal_stmt_node + new_body,
727 728
            decorator_list=[],
            returns=None,
729 730
            type_comment=None,
        )
731
        new_stmts.append(body_func_node)
732 733 734 735

        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())
736

737 738 739 740 741 742 743 744
        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,
        )
745
        new_stmts.extend([get_args_node, set_args_node])
746
        new_stmts.extend(while_loop_nodes)
747
        return new_stmts