Detect type of block structures and their boundaries to fix optimized jumps
        in python2.3+

def detect_control_flow(self, offset, op, extended_arg):
        """
        Detect type of block structures and their boundaries to fix optimized jumps
        in python2.3+
        """

        code = self.code

        # Detect parent structure
        parent = self.structs[0]
        start  = parent['start']
        end    = parent['end']

        # Pick inner-most parent for our offset
        for struct in self.structs:
            current_start = struct['start']
            current_end   = struct['end']
            if ((current_start <= offset < current_end)
                and (current_start >= start and current_end <= end)):
                start  = current_start
                end    = current_end
                parent = struct

        if op == self.opc.SETUP_LOOP:
            # We categorize loop types: 'for', 'while', 'while 1' with
            # possibly suffixes '-loop' and '-else'
            # Try to find the jump_back instruction of the loop.
            # It could be a return instruction.

            inst = self.insts[self.offset2inst_index[offset]]
            start += instruction_size(op, self.opc)
            setup_target = inst.argval
            loop_end_offset = self.restrict_to_parent(setup_target, parent)
            self.setup_loop_targets[offset] = setup_target
            self.setup_loops[setup_target] = offset

            if setup_target != loop_end_offset:
                self.fixed_jumps[offset] = loop_end_offset

            (line_no, next_line_byte) = self.lines[offset]

            # jump_back_offset is the instruction after the SETUP_LOOP
            # where we iterate back to.
            jump_back_offset = self.last_instr(start, loop_end_offset, self.opc.JUMP_ABSOLUTE,
                                        next_line_byte, False)

            if jump_back_offset:
                # Account for the fact that < 2.7 has an explicit
                # POP_TOP instruction in the equivalate POP_JUMP_IF
                # construct
                if self.version < 2.7:
                    jump_forward_offset = jump_back_offset+4
                    return_val_offset1 = self.prev[self.prev[self.prev[loop_end_offset]]]
                    # Is jump back really "back"?
                    jump_target = self.get_target(jump_back_offset, code[jump_back_offset])
                    if (jump_target > jump_back_offset or
                        code[jump_back_offset+3] in [self.opc.JUMP_FORWARD, self.opc.JUMP_ABSOLUTE]):
                        jump_back_offset = None
                        pass
                else:
                    jump_forward_offset = jump_back_offset+3
                    return_val_offset1 = self.prev[self.prev[loop_end_offset]]

            if (jump_back_offset and jump_back_offset != self.prev[loop_end_offset]
                and code[jump_forward_offset] in self.jump_forward):
                if (code[self.prev[loop_end_offset]] == self.opc.RETURN_VALUE or
                    (code[self.prev[loop_end_offset]] == self.opc.POP_BLOCK
                     and code[return_val_offset1] == self.opc.RETURN_VALUE)):
                    jump_back_offset = None

            if not jump_back_offset:
                # loop suite ends in return
                # scanner26 of wbiti had:
                # jump_back_offset = self.last_instr(start, loop_end_offset, self.opc.JUMP_ABSOLUTE, start, False)
                jump_back_offset = self.last_instr(start, loop_end_offset, self.opc.RETURN_VALUE)
                if not jump_back_offset:
                    return
                jump_back_offset += 1

                if_offset = None
                if self.version < 2.7:
                    # Look for JUMP_IF POP_TOP ...
                    if (code[self.prev[next_line_byte]] == self.opc.POP_TOP
                        and (code[self.prev[self.prev[next_line_byte]]]
                             in self.pop_jump_if)):
                        if_offset = self.prev[self.prev[next_line_byte]]
                elif code[self.prev[next_line_byte]] in self.pop_jump_if:
                    # Look for POP_JUMP_IF ...
                    if_offset = self.prev[next_line_byte]
                if if_offset:
                    loop_type = 'while'
                    self.ignore_if.add(if_offset)
                    if self.version < 2.7 and (
                            code[self.prev[jump_back_offset]] == self.opc.RETURN_VALUE):
                        self.ignore_if.add(self.prev[jump_back_offset])
                        pass
                    pass
                else:
                    loop_type = 'for'
                setup_target = next_line_byte
                loop_end_offset = jump_back_offset + 3
            else:
                # We have a loop with a jump-back instruction
                if self.get_target(jump_back_offset) >= next_line_byte:
                    jump_back_offset = self.last_instr(start, loop_end_offset, self.opc.JUMP_ABSOLUTE, start, False)
                if loop_end_offset > jump_back_offset+4 and code[loop_end_offset] in self.jump_forward:
                    if code[jump_back_offset+4] in self.jump_forward:
                        if self.get_target(jump_back_offset+4) == self.get_target(loop_end_offset):
                            self.fixed_jumps[offset] = jump_back_offset+4
                            loop_end_offset = jump_back_offset+4
                elif setup_target < offset:
                    self.fixed_jumps[offset] = jump_back_offset+4
                    loop_end_offset = jump_back_offset+4

                setup_target = self.get_target(jump_back_offset, self.opc.JUMP_ABSOLUTE)

                if (self.version > 2.1 and
                    code[setup_target] in (self.opc.FOR_ITER, self.opc.GET_ITER)):
                    loop_type = 'for'
                else:
                    loop_type = 'while'
                    # Look for a test condition immediately after the
                    # SETUP_LOOP while
                    if (self.version < 2.7
                        and self.code[self.prev[next_line_byte]] == self.opc.POP_TOP):
                        test_op_offset = self.prev[self.prev[next_line_byte]]
                    else:
                        test_op_offset = self.prev[next_line_byte]

                    if test_op_offset == offset:
                        loop_type = 'while 1'
                    elif self.code[test_op_offset] in self.opc.JUMP_OPs:
                        test_target = self.get_target(test_op_offset)

                        self.ignore_if.add(test_op_offset)

                        if test_target > (jump_back_offset+3):
                            jump_back_offset = test_target
                self.not_continue.add(jump_back_offset)
            self.loops.append(setup_target)
            self.structs.append({'type': loop_type + '-loop',
                                   'start': setup_target,
                                   'end':   jump_back_offset})
            if jump_back_offset+3 != loop_end_offset:
                self.structs.append({'type': loop_type + '-else',
                                       'start': jump_back_offset+3,
                                       'end':   loop_end_offset})
        elif op == self.opc.SETUP_EXCEPT:
            start  = offset + instruction_size(op, self.opc)
            target = self.get_target(offset, op)
            end_offset = self.restrict_to_parent(target, parent)
            if target != end_offset:
                self.fixed_jumps[offset] = end_offset
                # print target, end, parent
            # Add the try block
            self.structs.append({'type':  'try',
                                   'start': start-3,
                                   'end':   end_offset-4})
            # Now isolate the except and else blocks
            end_else = start_else = self.get_target(self.prev[end_offset])


            end_finally_offset = end_offset
            setup_except_nest = 0
            while end_finally_offset < len(self.code):
                if self.code[end_finally_offset] == self.opc.END_FINALLY:
                    if setup_except_nest == 0:
                        break
                    else:
                        setup_except_nest -= 1
                elif self.code[end_finally_offset] == self.opc.SETUP_EXCEPT:
                    setup_except_nest += 1
                end_finally_offset += instruction_size(code[end_finally_offset], self.opc)
                pass

            # Add the except blocks
            i = end_offset
            while i < len(self.code) and i < end_finally_offset:
                jmp = self.next_except_jump(i)
                if jmp is None: # check
                    i = self.next_stmt[i]
                    continue
                if self.code[jmp] == self.opc.RETURN_VALUE:
                    self.structs.append({'type':  'except',
                                           'start': i,
                                           'end':   jmp+1})
                    i = jmp + 1
                else:
                    target = self.get_target(jmp)
                    if target != start_else:
                        end_else = self.get_target(jmp)
                    if self.code[jmp] == self.opc.JUMP_FORWARD:
                        if self.version <= 2.6:
                            self.fixed_jumps[jmp] = target
                        else:
                            self.fixed_jumps[jmp] = -1
                    self.structs.append({'type':  'except',
                                   'start': i,
                                   'end':   jmp})
                    i = jmp + 3

            # Add the try-else block
            if end_else != start_else:
                r_end_else = self.restrict_to_parent(end_else, parent)
                # May be able to drop the 2.7 test.
                if self.version == 2.7:
                    self.structs.append({'type':  'try-else',
                                           'start': i+1,
                                           'end':   r_end_else})
                    self.fixed_jumps[i] = r_end_else
            else:
                self.fixed_jumps[i] = i+1

        elif op in self.pop_jump_if:
            target = self.get_target(offset, op)
            rtarget = self.restrict_to_parent(target, parent)

            # Do not let jump to go out of parent struct bounds
            if target != rtarget and parent['type'] == 'and/or':
                self.fixed_jumps[offset] = rtarget
                return

            jump_if_offset = offset

            start = offset+3
            pre = self.prev

            # Does this jump to right after another conditional jump that is
            # not myself?  If so, it's part of a larger conditional.
            # rocky: if we have a conditional jump to the next instruction, then
            # possibly I am "skipping over" a "pass" or null statement.

            test_target = target
            if self.version < 2.7:
                # Before 2.7 we have to deal with the fact that there is an extra
                # POP_TOP that is logically associated with the JUMP_IF's (even though
                # the instance set is called "self.pop_jump_if")
                if code[pre[test_target]] == self.opc.POP_TOP:
                    test_target = pre[test_target]
                test_set = self.pop_jump_if
            else:
                test_set = self.pop_jump_if_or_pop | self.pop_jump_if

            if ( code[pre[test_target]] in test_set and target > offset ):
                # We have POP_JUMP_IF... target
                # ...
                # pre: POP_JUMP_IF ...
                # target: ...
                #
                # We will take that as either as "and" or "or".
                self.fixed_jumps[offset] = pre[target]
                self.structs.append({'type':  'and/or',
                                     'start': start,
                                     'end':   pre[target]})
                return

            # The instruction offset just before the target jump offset is important
            # in making a determination of what we have. Save that.
            pre_rtarget = pre[rtarget]

            # Is it an "and" inside an "if" or "while" block
            if op == self.opc.PJIF:

                # Search for other POP_JUMP_IF_...'s targetting the
                # same target, of the current POP_JUMP_... instruction,
                # starting from current offset, and filter everything inside inner 'or'
                # jumps and mid-line ifs
                match = self.rem_or(start, self.next_stmt[offset], self.opc.PJIF, target)

                # If we still have any offsets in set, start working on it
                if match:
                    if code[pre_rtarget] in self.jump_forward \
                            and pre_rtarget not in self.stmts \
                            and self.restrict_to_parent(self.get_target(pre_rtarget), parent) == rtarget:
                        if code[pre[pre_rtarget]] == self.opc.JUMP_ABSOLUTE \
                                and self.remove_mid_line_ifs([offset]) \
                                and target == self.get_target(pre[pre_rtarget]) \
                                and (pre[pre_rtarget] not in self.stmts or self.get_target(pre[pre_rtarget]) > pre[pre_rtarget])\
                                and 1 == len(self.remove_mid_line_ifs(self.rem_or(start, pre[pre_rtarget], self.pop_jump_if, target))):
                            pass
                        elif code[pre[pre_rtarget]] == self.opc.RETURN_VALUE \
                                and self.remove_mid_line_ifs([offset]) \
                                and 1 == (len(set(self.remove_mid_line_ifs(self.rem_or(start,
                                                                                       pre[pre_rtarget],
                                                                                       self.pop_jump_if, target)))
                                              | set(self.remove_mid_line_ifs(self.rem_or(start, pre[pre_rtarget],
                                                            (self.opc.PJIF, self.opc.PJIT, self.opc.JUMP_ABSOLUTE), pre_rtarget, True))))):
                            pass
                        else:
                            fix = None
                            jump_ifs = self.all_instr(start, self.next_stmt[offset], self.opc.PJIF)
                            last_jump_good = True
                            for j in jump_ifs:
                                if target == self.get_target(j):
                                    if self.lines[j].next == j+3 and last_jump_good:
                                        fix = j
                                        break
                                else:
                                    last_jump_good = False
                            self.fixed_jumps[offset] = fix or match[-1]
                            return
                    else:
                        if (self.version < 2.7
                            and parent['type'] in ('root', 'for-loop', 'if-then',
                                                   'else', 'try')):
                            self.fixed_jumps[offset] = rtarget
                        else:
                            # note test for < 2.7 might be superflous although informative
                            # for 2.7 a different branch is taken and the below code is handled
                            # under: elif op in self.pop_jump_if_or_pop
                            # below
                            self.fixed_jumps[offset] = match[-1]
                        return
            else: # op != self.opc.PJIT
                if self.version < 2.7 and code[offset+3] == self.opc.POP_TOP:
                    assert_offset = offset + 4
                else:
                    assert_offset = offset + 3
                if (assert_offset) in self.load_asserts:
                    if code[pre_rtarget] == self.opc.RAISE_VARARGS:
                        return
                    self.load_asserts.remove(assert_offset)

                next = self.next_stmt[offset]
                if pre[next] == offset:
                    pass
                elif code[next] in self.jump_forward and target == self.get_target(next):
                    if code[pre[next]] == self.opc.PJIF:
                        if code[next] == self.opc.JUMP_FORWARD or target != rtarget or code[pre[pre_rtarget]] not in (self.opc.JUMP_ABSOLUTE, self.opc.RETURN_VALUE):
                            self.fixed_jumps[offset] = pre[next]
                            return
                elif code[next] == self.opc.JUMP_ABSOLUTE and code[target] in self.jump_forward:
                    next_target = self.get_target(next)
                    if self.get_target(target) == next_target:
                        self.fixed_jumps[offset] = pre[next]
                        return
                    elif code[next_target] in self.jump_forward and self.get_target(next_target) == self.get_target(target):
                        self.fixed_jumps[offset] = pre[next]
                        return

            # don't add a struct for a while test, it's already taken care of
            if offset in self.ignore_if:
                return

            if self.version == 2.7:
                if code[pre_rtarget] == self.opc.JUMP_ABSOLUTE and pre_rtarget in self.stmts \
                        and pre_rtarget != offset and pre[pre_rtarget] != offset:
                    if code[rtarget] == self.opc.JUMP_ABSOLUTE and code[rtarget+3] == self.opc.POP_BLOCK:
                        if code[pre[pre_rtarget]] != self.opc.JUMP_ABSOLUTE:
                            pass
                        elif self.get_target(pre[pre_rtarget]) != target:
                            pass
                        else:
                            rtarget = pre_rtarget
                    else:
                        rtarget = pre_rtarget
                    pre_rtarget = pre[rtarget]

            # Does the "jump if" jump beyond a jump op?
            # That is, we have something like:
            #  POP_JUMP_IF_FALSE HERE
            #  ...
            # JUMP_FORWARD
            # HERE:
            #
            # If so, this can be a block inside an "if" statement
            # or a conditional assignment like:
            #   x = 1 if x else 2
            #
            # There are other situations we may need to consider, like
            # if the condition jump is to a forward location.
            # Also the existence of a jump to the instruction after "END_FINALLY"
            # will distinguish "try/else" from "try".
            code_pre_rtarget = code[pre_rtarget]

            if code_pre_rtarget in self.jump_forward:
                if_end = self.get_target(pre_rtarget)

                # Is this a loop and not an "if" statment?
                if (if_end < pre_rtarget) and (pre[if_end] in self.setup_loop_targets):

                    if (if_end > start):
                        return
                    else:
                        # We still have the case in 2.7 that the next instruction
                        # is a jump to a SETUP_LOOP target.
                        next_offset = target + instruction_size(self.code[target], self.opc)
                        next_op = self.code[next_offset]
                        if self.op_name(next_op) == 'JUMP_FORWARD':
                            jump_target = self.get_target(next_offset, next_op)
                            if jump_target in self.setup_loops:
                                self.structs.append({'type':  'while-loop',
                                       'start': jump_if_offset,
                                       'end':   jump_target})
                                self.fixed_jumps[jump_if_offset] = jump_target
                                return

                end_offset = self.restrict_to_parent(if_end, parent)

                if_then_maybe = None

                if 2.2 <= self.version <= 2.6:
                    # Take the JUMP_IF target. In an "if/then", it will be
                    # a POP_TOP instruction and the instruction before it
                    # will be a JUMP_FORWARD to just after the POP_TOP.
                    # For example:
                    # Good:
                    # 3  JUMP_IF_FALSE        33  'to 39'
                    # ..
                    # 36  JUMP_FORWARD          1  'to 40'
                    # 39  POP_TOP
                    # 40 ...
                    # example:

                    # BAD (is an "and"):
                    # 28  JUMP_IF_FALSE         4  'to 35'
                    # ...
                    # 32  JUMP_ABSOLUTE        40  'to 40' # should be 36 or there should
                    #                                      # be a COME_FROM at the pop top
                    #                                      # before 40 to 35
                    # 35  POP_TOP
                    # 36 ...
                    # 39  POP_TOP
                    # 39_0  COME_FROM 3
                    # 40 ...

                    if self.opname_for_offset(jump_if_offset).startswith('JUMP_IF'):
                        jump_if_target = code[jump_if_offset+1]
                        if self.opname_for_offset(jump_if_target + jump_if_offset + 3) == 'POP_TOP':
                            jump_inst = jump_if_target + jump_if_offset
                            jump_offset = code[jump_inst+1]
                            jump_op = self.opname_for_offset(jump_inst)
                            if (jump_op == 'JUMP_FORWARD' and jump_offset == 1):
                                self.structs.append({'type':  'if-then',
                                                     'start': start-3,
                                                     'end':   pre_rtarget})
                                self.thens[start] = end_offset
                            elif jump_op == 'JUMP_ABSOLUTE':
                                if_then_maybe = {'type':  'if-then',
                                                 'start': start-3,
                                                 'end':   pre_rtarget}

                elif self.version == 2.7:
                    self.structs.append({'type':  'if-then',
                                         'start': start-3,
                                         'end':   pre_rtarget})

                # FIXME: this is yet another case were we need dominators.
                if (pre_rtarget not in self.linestarts
                    or self.version < 2.7):
                    self.not_continue.add(pre_rtarget)

                if rtarget < end_offset:
                    # We have an "else" block  of some kind.
                    # Is it associated with "if_then_maybe" seen above?
                    # These will be linked in this funny way:

                    # 198  JUMP_IF_FALSE        18  'to 219'
                    # 201  POP_TOP
                    # ...
                    # 216  JUMP_ABSOLUTE       256  'to 256'
                    # 219  POP_TOP
                    # ...
                    # 252  JUMP_FORWARD          1  'to 256'
                    # 255  POP_TOP
                    # 256
                    if if_then_maybe and jump_op == 'JUMP_ABSOLUTE':
                        jump_target = self.get_target(jump_inst, code[jump_inst])
                        if self.opname_for_offset(end_offset) == 'JUMP_FORWARD':
                            end_target = self.get_target(end_offset, code[end_offset])
                            if jump_target == end_target:
                                self.structs.append(if_then_maybe)
                                self.thens[start] = end_offset

                    self.structs.append({'type':  'else',
                                       'start': rtarget,
                                       'end':   end_offset})
            elif code_pre_rtarget == self.opc.RETURN_VALUE:
                if self.version == 2.7 or pre_rtarget not in self.ignore_if:
                    # Below, 10 is exception-match. If there is an exception
                    # match in the compare, then this is an exception
                    # clause not an if-then clause
                    if (self.code[self.prev[offset]] != self.opc.COMPARE_OP or
                        self.code[self.prev[offset]+1] != 10):
                        self.structs.append({'type':  'if-then',
                                               'start': start,
                                               'end':   rtarget})
                        self.thens[start] = rtarget
                        if (self.version == 2.7 or
                            code[pre_rtarget+1] != self.opc.JUMP_FORWARD):
                            # The below is a big hack until we get
                            # better control flow analysis: disallow
                            # END_IF if the instruction before the
                            # END_IF instruction happens to be a jump
                            # target. In this case, probably what's
                            # gone on is that we messed up on the
                            # END_IF location and it should be the
                            # instruction before.
                            self.fixed_jumps[offset] = rtarget
                            if (self.version == 2.7 and
                                self.insts[self.offset2inst_index[pre[pre_rtarget]]].is_jump_target):
                                self.return_end_ifs.add(pre[pre_rtarget])
                                pass
                            else:
                                self.return_end_ifs.add(pre_rtarget)
                            pass
                        pass
                    pass

        elif op in self.pop_jump_if_or_pop:
            target = self.get_target(offset, op)
            self.fixed_jumps[offset] = self.restrict_to_parent(target, parent)