Changeset 34c32f0 for src/ControlStruct


Ignore:
Timestamp:
Feb 1, 2022, 12:06:24 PM (3 years ago)
Author:
caparsons <caparson@…>
Branches:
ADT, ast-experimental, enum, forall-pointer-decay, master, pthread-emulation, qualifiedEnum
Children:
ab1a9ea
Parents:
3e5db5b4 (diff), 7b2c8c3c (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

Location:
src/ControlStruct
Files:
2 added
13 edited

Legend:

Unmodified
Added
Removed
  • TabularUnified src/ControlStruct/ExceptTranslateNew.cpp

    r3e5db5b4 r34c32f0  
    99// Author           : Andrew Beach
    1010// Created On       : Mon Nov  8 11:53:00 2021
    11 // Last Modified By : Andrew Beach
    12 // Last Modified On : Mon Nov  8 16:50:00 2021
    13 // Update Count     : 0
     11// Last Modified By : Peter A. Buhr
     12// Last Modified On : Mon Jan 31 18:49:58 2022
     13// Update Count     : 1
    1414//
    1515
     
    2222
    2323namespace ControlStruct {
    24 
    25 namespace {
    2624
    2725class TranslateThrowsCore : public ast::WithGuards {
     
    128126}
    129127
    130 } // namespace
    131 
    132128void translateThrows( ast::TranslationUnit & transUnit ) {
    133129        ast::Pass<TranslateThrowsCore>::run( transUnit );
  • TabularUnified src/ControlStruct/FixLabels.cpp

    r3e5db5b4 r34c32f0  
    99// Author           : Andrew Beach
    1010// Created On       : Mon Nov  1 09:39:00 2021
    11 // Last Modified By : Andrew Beach
    12 // Last Modified On : Mon Nov  8 10:53:00 2021
    13 // Update Count     : 3
     11// Last Modified By : Peter A. Buhr
     12// Last Modified On : Mon Jan 31 22:19:17 2022
     13// Update Count     : 9
    1414//
    1515
     
    2020#include "AST/Stmt.hpp"
    2121#include "ControlStruct/MultiLevelExit.hpp"
     22using namespace ast;
    2223
    2324namespace ControlStruct {
    24 
    25 namespace {
    26 
    27 class FixLabelsCore final : public ast::WithGuards {
     25class FixLabelsCore final : public WithGuards {
    2826        LabelToStmt labelTable;
    29 public:
     27  public:
    3028        FixLabelsCore() : labelTable() {}
    3129
    32         void previsit( const ast::FunctionDecl * );
    33         const ast::FunctionDecl * postvisit( const ast::FunctionDecl * );
    34         void previsit( const ast::Stmt * );
    35         void previsit( const ast::BranchStmt * );
    36         void previsit( const ast::LabelAddressExpr * );
     30        void previsit( const FunctionDecl * );
     31        const FunctionDecl * postvisit( const FunctionDecl * );
     32        void previsit( const Stmt * );
     33        void previsit( const BranchStmt * );
     34        void previsit( const LabelAddressExpr * );
    3735
    38         void setLabelsDef( const std::vector<ast::Label> &, const ast::Stmt * );
    39         void setLabelsUsage( const ast::Label & );
     36        void setLabelsDef( const std::vector<Label> &, const Stmt * );
     37        void setLabelsUsage( const Label & );
    4038};
    4139
    42 void FixLabelsCore::previsit( const ast::FunctionDecl * ) {
     40void FixLabelsCore::previsit( const FunctionDecl * ) {
    4341        GuardValue( labelTable ).clear();
    4442}
    4543
    46 const ast::FunctionDecl * FixLabelsCore::postvisit(
    47                 const ast::FunctionDecl * decl ) {
     44const FunctionDecl * FixLabelsCore::postvisit(
     45        const FunctionDecl * decl ) {
    4846        if ( nullptr == decl->stmts ) return decl;
    4947        for ( auto kvp : labelTable ) {
    5048                if ( nullptr == kvp.second ) {
    5149                        SemanticError( kvp.first.location,
    52                                 "Use of undefined label: " + kvp.first.name );
     50                                                   "Use of undefined label: " + kvp.first.name );
    5351                }
    5452        }
    55         return ast::mutate_field( decl, &ast::FunctionDecl::stmts,
    56                 multiLevelExitUpdate( decl->stmts.get(), labelTable ) );
     53        return mutate_field( decl, &FunctionDecl::stmts,
     54                                                 multiLevelExitUpdate( decl->stmts.get(), labelTable ) );
    5755}
    5856
    59 void FixLabelsCore::previsit( const ast::Stmt * stmt ) {
     57void FixLabelsCore::previsit( const Stmt * stmt ) {
    6058        if ( !stmt->labels.empty() ) {
    6159                setLabelsDef( stmt->labels, stmt );
     
    6361}
    6462
    65 void FixLabelsCore::previsit( const ast::BranchStmt * stmt ) {
     63void FixLabelsCore::previsit( const BranchStmt * stmt ) {
    6664        if ( !stmt->labels.empty() ) {
    6765                setLabelsDef( stmt->labels, stmt );
     
    7270}
    7371
    74 void FixLabelsCore::previsit( const ast::LabelAddressExpr * expr ) {
     72void FixLabelsCore::previsit( const LabelAddressExpr * expr ) {
    7573        assert( !expr->arg.empty() );
    7674        setLabelsUsage( expr->arg );
     
    7876
    7977void FixLabelsCore::setLabelsDef(
    80                 const std::vector<ast::Label> & labels, const ast::Stmt * stmt ) {
     78        const std::vector<Label> & labels, const Stmt * stmt ) {
    8179        assert( !labels.empty() );
    8280        assert( stmt );
     
    8987                        // Duplicate definition, this is an error.
    9088                        SemanticError( label.location,
    91                                 "Duplicate definition of label: " + label.name );
     89                                                   "Duplicate definition of label: " + label.name );
    9290                } else {
    9391                        // Perviously used, but not defined until now.
     
    9896
    9997// Label was used, if it is new add it to the table.
    100 void FixLabelsCore::setLabelsUsage( const ast::Label & label ) {
     98void FixLabelsCore::setLabelsUsage( const Label & label ) {
    10199        if ( labelTable.find( label ) == labelTable.end() ) {
    102100                labelTable[ label ] = nullptr;
     
    104102}
    105103
    106 } // namespace
    107 
    108 void fixLabels( ast::TranslationUnit & translationUnit ) {
    109         ast::Pass<FixLabelsCore>::run( translationUnit );
     104void fixLabels( TranslationUnit & translationUnit ) {
     105        Pass<FixLabelsCore>::run( translationUnit );
    110106}
    111 
    112107} // namespace ControlStruct
    113108
  • TabularUnified src/ControlStruct/FixLabels.hpp

    r3e5db5b4 r34c32f0  
    99// Author           : Andrew Beach
    1010// Created On       : Mon Nov  1 09:36:00 2021
    11 // Last Modified By : Andrew Beach
    12 // Last Modified On : Mon Nov  1 09:40:00 2021
    13 // Update Count     : 0
     11// Last Modified By : Peter A. Buhr
     12// Last Modified On : Mon Jan 31 22:18:43 2022
     13// Update Count     : 2
    1414//
    1515
     
    1717
    1818namespace ast {
    19         class TranslationUnit;
     19class TranslationUnit;
    2020}
    2121
    2222namespace ControlStruct {
    23 
    24 /// normalizes label definitions and generates multi-level exit labels
     23// normalizes label definitions and generates multi-level exit labels
    2524void fixLabels( ast::TranslationUnit & translationUnit );
    26 
    2725}
    2826
  • TabularUnified src/ControlStruct/ForExprMutator.h

    r3e5db5b4 r34c32f0  
    1010// Created On       : Mon May 18 07:44:20 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Thu Aug 17 15:32:48 2017
    13 // Update Count     : 5
     12// Last Modified On : Sun Jan 30 09:14:46 2022
     13// Update Count     : 6
    1414//
    1515
     
    2424        class ForExprMutator {
    2525          public:
    26                 Statement *postmutate( IfStmt * );
    27                 Statement *postmutate( ForStmt * );
    28                 Statement *postmutate( WhileStmt * );
     26                Statement * postmutate( IfStmt * );
     27                Statement * postmutate( ForStmt * );
     28                Statement * postmutate( WhileStmt * );
    2929        };
    3030} // namespace ControlStruct
  • TabularUnified src/ControlStruct/HoistControlDecls.cpp

    r3e5db5b4 r34c32f0  
    99// Author           : Andrew Beach
    1010// Created On       : Fri Dec  3 15:34:00 2021
    11 // Last Modified By : Andrew Beach
    12 // Last Modified On : Fri Dec  3 15:34:00 2021
    13 // Update Count     : 0
     11// Last Modified By : Peter A. Buhr
     12// Last Modified On : Mon Jan 31 18:52:35 2022
     13// Update Count     : 23
    1414//
    1515
     
    1919#include "AST/Pass.hpp"
    2020#include "AST/TranslationUnit.hpp"
     21using namespace ast;
    2122
    2223namespace ControlStruct {
    2324
    24 namespace {
     25template<typename StmtT>
     26const Stmt * hoist( const StmtT * stmt ) {
     27        // If no hoisting is needed, then make no changes.
    2528
    26 template<typename StmtT>
    27 const ast::Stmt * hoist( const StmtT * stmt ) {
    28         // If no hoisting is needed, then make no changes.
    29         if ( 0 == stmt->inits.size() ) {
     29        if ( stmt->inits.size() == 0 ) {                                        // no declarations ?
     30                // if ( /* no conditional declarations */ ...  ) ...
    3031                return stmt;
    31         }
     32        } // if
    3233
    33         // Put initializers and the old statement in the compound statement.
    34         ast::CompoundStmt * block = new ast::CompoundStmt( stmt->location );
    35         StmtT * mutStmt = ast::mutate( stmt );
    36         for ( const ast::Stmt * next : mutStmt->inits ) {
     34        // Put hoist declarations and modified statement in a compound statement.
     35
     36        CompoundStmt * block = new CompoundStmt( stmt->location ); // create empty compound statement
     37        //    {
     38        //    }
     39
     40        for ( const Stmt * next : stmt->inits ) {                       // link conditional declarations into compound
    3741                block->kids.push_back( next );
    3842        }
    39         mutStmt->inits.clear();
    40         block->kids.push_back( mutStmt );
     43        //    if ( int x = f(), y = g(); ... ) ...
     44        // link declarations into compound statement
     45        //    {
     46        //         int x = f();
     47        //         int y = g();
     48        //    }
     49
     50        StmtT * mutStmt = mutate( stmt );                                       // create mutate handle to change statement
     51        mutStmt->inits.clear();                                                         // remove declarations
     52        //    if ( ... ) ...
     53
     54        block->kids.push_back( mutStmt );                                       // link modified statement into compound
     55        //    {
     56        //        int x = f();
     57        //        int y = g();
     58        //        if ( ... ) ...
     59        //    }
    4160        return block;
    4261}
    4362
    44 struct HoistControlCore {
    45         const ast::Stmt * postvisit( const ast::IfStmt * stmt ) {
    46                 return hoist<ast::IfStmt>( stmt );
     63struct hoistControlDeclsCore {
     64        // Statements with declarations in conditional.
     65        const Stmt * postvisit( const IfStmt * stmt ) {
     66                return hoist<IfStmt>( stmt );
    4767        }
    48         const ast::Stmt * postvisit( const ast::ForStmt * stmt ) {
    49                 return hoist<ast::ForStmt>( stmt );
     68        const Stmt * postvisit( const ForStmt * stmt ) {
     69                return hoist<ForStmt>( stmt );
    5070        }
    51         const ast::Stmt * postvisit( const ast::WhileStmt * stmt ) {
    52                 return hoist<ast::WhileStmt>( stmt );
     71        const Stmt * postvisit( const WhileStmt * stmt ) {
     72                return hoist<WhileStmt>( stmt );
    5373        }
    5474};
    5575
    56 } // namespace
    57 
    58 /// Hoist initialization out of for statements.
    59 void hoistControlDecls( ast::TranslationUnit & translationUnit ) {
    60         ast::Pass<HoistControlCore>::run( translationUnit );
     76// Hoist initialization out of for statements.
     77void hoistControlDecls( TranslationUnit & translationUnit ) {
     78        Pass<hoistControlDeclsCore>::run( translationUnit );
    6179}
    6280
  • TabularUnified src/ControlStruct/HoistControlDecls.hpp

    r3e5db5b4 r34c32f0  
    99// Author           : Andrew Beach
    1010// Created On       : Fri Dec  3 15:31:00 2021
    11 // Last Modified By : Andrew Beach
    12 // Last Modified On : Fri Dec  3 15:31:00 2021
    13 // Update Count     : 0
     11// Last Modified By : Peter A. Buhr
     12// Last Modified On : Mon Jan 31 22:25:07 2022
     13// Update Count     : 3
    1414//
    1515
     
    1717
    1818namespace ast {
    19         class TranslationUnit;
     19class TranslationUnit;
    2020}
    2121
    2222namespace ControlStruct {
    23 
    24 /// Hoist initialization out of control flow statements.
     23// Hoist declarations out of control flow statements into compound statement.
    2524void hoistControlDecls( ast::TranslationUnit & translationUnit );
    26 
    2725} // namespace ControlStruct
    2826
  • TabularUnified src/ControlStruct/LabelFixer.cc

    r3e5db5b4 r34c32f0  
    99// Author           : Rodolfo G. Esteves
    1010// Created On       : Mon May 18 07:44:20 2015
    11 // Last Modified By : Andrew Beach
    12 // Last Modified On : Tue Jan 21 10:32:00 2020
    13 // Update Count     : 160
     11// Last Modified By : Peter A. Buhr
     12// Last Modified On : Mon Jan 31 22:28:31 2022
     13// Update Count     : 161
    1414//
    1515
     
    2727
    2828namespace ControlStruct {
    29         bool LabelFixer::Entry::insideLoop() {
    30                 return ( dynamic_cast< ForStmt * > ( definition ) ||
    31                         dynamic_cast< WhileStmt * > ( definition )  );
     29bool LabelFixer::Entry::insideLoop() {
     30        return ( dynamic_cast< ForStmt * > ( definition ) ||
     31                dynamic_cast< WhileStmt * > ( definition )  );
     32}
     33
     34LabelFixer::LabelFixer( LabelGenerator * gen ) : generator ( gen ) {
     35        if ( generator == 0 )
     36                generator = LabelGenerator::getGenerator();
     37}
     38
     39void LabelFixer::previsit( FunctionDecl * ) {
     40        // need to go into a nested function in a fresh state
     41        GuardValue( labelTable );
     42        labelTable.clear();
     43}
     44
     45void LabelFixer::postvisit( FunctionDecl * functionDecl ) {
     46        PassVisitor<MultiLevelExitMutator> mlem( resolveJumps(), generator );
     47        // We start in the body so we can stop when we hit another FunctionDecl.
     48        maybeMutate( functionDecl->statements, mlem );
     49}
     50
     51// prune to at most one label definition for each statement
     52void LabelFixer::previsit( Statement * stmt ) {
     53        std::list< Label > &labels = stmt->get_labels();
     54
     55        if ( ! labels.empty() ) {
     56                // only remember one label for each statement
     57                Label current = setLabelsDef( labels, stmt );
     58        } // if
     59}
     60
     61void LabelFixer::previsit( BranchStmt * branchStmt ) {
     62        previsit( ( Statement *)branchStmt );
     63
     64        // for labeled branches, add an entry to the label table
     65        Label target = branchStmt->get_target();
     66        if ( target != "" ) {
     67                setLabelsUsg( target, branchStmt );
     68        }
     69}
     70
     71void LabelFixer::previsit( LabelAddressExpr * addrExpr ) {
     72        Label & target = addrExpr->arg;
     73        assert( target != "" );
     74        setLabelsUsg( target, addrExpr );
     75}
     76
     77
     78// Sets the definition of the labelTable entry to be the provided statement for every label in
     79// the list parameter. Happens for every kind of statement.
     80Label LabelFixer::setLabelsDef( std::list< Label > & llabel, Statement * definition ) {
     81        assert( definition != 0 );
     82        assert( llabel.size() > 0 );
     83
     84        for ( std::list< Label >::iterator i = llabel.begin(); i != llabel.end(); i++ ) {
     85                Label & l = *i;
     86                l.set_statement( definition ); // attach statement to the label to be used later
     87                if ( labelTable.find( l ) == labelTable.end() ) {
     88                        // All labels on this statement need to use the same entry,
     89                        // so this should only be created once.
     90                        // undefined and unused until now, add an entry
     91                        labelTable[ l ] = new Entry( definition );
     92                } else if ( labelTable[ l ]->defined() ) {
     93                        // defined twice, error
     94                        SemanticError( l.get_statement()->location,
     95                                "Duplicate definition of label: " + l.get_name() );
     96                } else {
     97                        // used previously, but undefined until now -> link with this entry
     98                        // Question: Is changing objects important?
     99                        delete labelTable[ l ];
     100                        labelTable[ l ] = new Entry( definition );
     101                } // if
     102        } // for
     103
     104        // Produce one of the labels attached to this statement to be temporarily used as the
     105        // canonical label.
     106        return labelTable[ llabel.front() ]->get_label();
     107}
     108
     109// A label was used, add it to the table if it isn't already there
     110template< typename UsageNode >
     111void LabelFixer::setLabelsUsg( Label orgValue, UsageNode *use ) {
     112        assert( use != 0 );
     113
     114        // add label with an unknown origin
     115        if ( labelTable.find( orgValue ) == labelTable.end() ) {
     116                labelTable[ orgValue ] = new Entry( 0 );
     117        }
     118}
     119
     120// Builds a table that maps a label to its defining statement.
     121std::map<Label, Statement * > * LabelFixer::resolveJumps() throw ( SemanticErrorException ) {
     122        std::map< Label, Statement * > *ret = new std::map< Label, Statement * >();
     123        for ( std::map< Label, Entry * >::iterator i = labelTable.begin(); i != labelTable.end(); ++i ) {
     124                if ( ! i->second->defined() ) {
     125                        SemanticError( i->first.get_statement()->location, "Use of undefined label: " + i->first.get_name() );
     126                }
     127                (*ret)[ i->first ] = i->second->get_definition();
    32128        }
    33129
    34         LabelFixer::LabelFixer( LabelGenerator * gen ) : generator ( gen ) {
    35                 if ( generator == 0 )
    36                         generator = LabelGenerator::getGenerator();
    37         }
    38 
    39         void LabelFixer::previsit( FunctionDecl * ) {
    40                 // need to go into a nested function in a fresh state
    41                 GuardValue( labelTable );
    42                 labelTable.clear();
    43         }
    44 
    45         void LabelFixer::postvisit( FunctionDecl * functionDecl ) {
    46                 PassVisitor<MultiLevelExitMutator> mlem( resolveJumps(), generator );
    47                 // We start in the body so we can stop when we hit another FunctionDecl.
    48                 maybeMutate( functionDecl->statements, mlem );
    49         }
    50 
    51         // prune to at most one label definition for each statement
    52         void LabelFixer::previsit( Statement * stmt ) {
    53                 std::list< Label > &labels = stmt->get_labels();
    54 
    55                 if ( ! labels.empty() ) {
    56                         // only remember one label for each statement
    57                         Label current = setLabelsDef( labels, stmt );
    58                 } // if
    59         }
    60 
    61         void LabelFixer::previsit( BranchStmt * branchStmt ) {
    62                 previsit( ( Statement *)branchStmt );
    63 
    64                 // for labeled branches, add an entry to the label table
    65                 Label target = branchStmt->get_target();
    66                 if ( target != "" ) {
    67                         setLabelsUsg( target, branchStmt );
    68                 }
    69         }
    70 
    71         void LabelFixer::previsit( LabelAddressExpr * addrExpr ) {
    72                 Label & target = addrExpr->arg;
    73                 assert( target != "" );
    74                 setLabelsUsg( target, addrExpr );
    75         }
    76 
    77 
    78         // Sets the definition of the labelTable entry to be the provided statement for every label in
    79         // the list parameter. Happens for every kind of statement.
    80         Label LabelFixer::setLabelsDef( std::list< Label > & llabel, Statement * definition ) {
    81                 assert( definition != 0 );
    82                 assert( llabel.size() > 0 );
    83 
    84                 for ( std::list< Label >::iterator i = llabel.begin(); i != llabel.end(); i++ ) {
    85                         Label & l = *i;
    86                         l.set_statement( definition ); // attach statement to the label to be used later
    87                         if ( labelTable.find( l ) == labelTable.end() ) {
    88                                 // All labels on this statement need to use the same entry,
    89                                 // so this should only be created once.
    90                                 // undefined and unused until now, add an entry
    91                                 labelTable[ l ] = new Entry( definition );
    92                         } else if ( labelTable[ l ]->defined() ) {
    93                                 // defined twice, error
    94                                 SemanticError( l.get_statement()->location,
    95                                         "Duplicate definition of label: " + l.get_name() );
    96                         } else {
    97                                 // used previously, but undefined until now -> link with this entry
    98                                 // Question: Is changing objects important?
    99                                 delete labelTable[ l ];
    100                                 labelTable[ l ] = new Entry( definition );
    101                         } // if
    102                 } // for
    103 
    104                 // Produce one of the labels attached to this statement to be temporarily used as the
    105                 // canonical label.
    106                 return labelTable[ llabel.front() ]->get_label();
    107         }
    108 
    109         // A label was used, add it to the table if it isn't already there
    110         template< typename UsageNode >
    111         void LabelFixer::setLabelsUsg( Label orgValue, UsageNode *use ) {
    112                 assert( use != 0 );
    113 
    114                 // add label with an unknown origin
    115                 if ( labelTable.find( orgValue ) == labelTable.end() ) {
    116                         labelTable[ orgValue ] = new Entry( 0 );
    117                 }
    118         }
    119 
    120         // Builds a table that maps a label to its defining statement.
    121         std::map<Label, Statement * > * LabelFixer::resolveJumps() throw ( SemanticErrorException ) {
    122                 std::map< Label, Statement * > *ret = new std::map< Label, Statement * >();
    123                 for ( std::map< Label, Entry * >::iterator i = labelTable.begin(); i != labelTable.end(); ++i ) {
    124                         if ( ! i->second->defined() ) {
    125                                 SemanticError( i->first.get_statement()->location, "Use of undefined label: " + i->first.get_name() );
    126                         }
    127                         (*ret)[ i->first ] = i->second->get_definition();
    128                 }
    129 
    130                 return ret;
    131         }
     130        return ret;
     131}
    132132}  // namespace ControlStruct
    133133
  • TabularUnified src/ControlStruct/LabelFixer.h

    r3e5db5b4 r34c32f0  
    1010// Created On       : Mon May 18 07:44:20 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Sat Jul 22 09:17:24 2017
    13 // Update Count     : 34
     12// Last Modified On : Mon Jan 31 22:28:04 2022
     13// Update Count     : 35
    1414//
    1515
     
    2626
    2727namespace ControlStruct {
    28         /// normalizes label definitions and generates multi-level exit labels
    29         class LabelGenerator;
     28// normalizes label definitions and generates multi-level exit labels
     29class LabelGenerator;
    3030
    31         class LabelFixer final : public WithGuards {
    32           public:
    33                 LabelFixer( LabelGenerator *gen = 0 );
     31class LabelFixer final : public WithGuards {
     32  public:
     33        LabelFixer( LabelGenerator *gen = 0 );
    3434
    35                 std::map < Label, Statement * > *resolveJumps() throw ( SemanticErrorException );
     35        std::map < Label, Statement * > *resolveJumps() throw ( SemanticErrorException );
    3636
    37                 // Declarations
    38                 void previsit( FunctionDecl *functionDecl );
    39                 void postvisit( FunctionDecl *functionDecl );
     37        // Declarations
     38        void previsit( FunctionDecl *functionDecl );
     39        void postvisit( FunctionDecl *functionDecl );
    4040
    41                 // Statements
    42                 void previsit( Statement *stmt );
    43                 void previsit( BranchStmt *branchStmt );
     41        // Statements
     42        void previsit( Statement *stmt );
     43        void previsit( BranchStmt *branchStmt );
    4444
    45                 // Expressions
    46                 void previsit( LabelAddressExpr *addrExpr );
     45        // Expressions
     46        void previsit( LabelAddressExpr *addrExpr );
    4747
    48                 Label setLabelsDef( std::list< Label > &, Statement *definition );
    49                 template< typename UsageNode >
    50                 void setLabelsUsg( Label, UsageNode *usage = 0 );
     48        Label setLabelsDef( std::list< Label > &, Statement *definition );
     49        template< typename UsageNode >
     50        void setLabelsUsg( Label, UsageNode *usage = 0 );
     51
     52  private:
     53        class Entry {
     54                public:
     55                Entry( Statement *to ) : definition( to ) {}
     56                bool defined() { return ( definition != 0 ); }
     57                bool insideLoop();
     58
     59                Label get_label() const { return label; }
     60                void set_label( Label lab ) { label = lab; }
     61
     62                Statement *get_definition() const { return definition; }
     63                void set_definition( Statement *def ) { definition = def; }
    5164
    5265          private:
    53                 class Entry {
    54                         public:
    55                         Entry( Statement *to ) : definition( to ) {}
    56                         bool defined() { return ( definition != 0 ); }
    57                         bool insideLoop();
     66                Label label;
     67                Statement *definition;
     68        };
    5869
    59                         Label get_label() const { return label; }
    60                         void set_label( Label lab ) { label = lab; }
    61 
    62                         Statement *get_definition() const { return definition; }
    63                         void set_definition( Statement *def ) { definition = def; }
    64 
    65                   private:
    66                         Label label;
    67                         Statement *definition;
    68                 };
    69 
    70                 std::map < Label, Entry *> labelTable;
    71                 LabelGenerator *generator;
    72         };
     70        std::map < Label, Entry *> labelTable;
     71        LabelGenerator *generator;
     72};
    7373} // namespace ControlStruct
    7474
  • TabularUnified src/ControlStruct/LabelGenerator.cc

    r3e5db5b4 r34c32f0  
    99// Author           : Rodolfo G. Esteves
    1010// Created On       : Mon May 18 07:44:20 2015
    11 // Last Modified By : Andrew Beach
    12 // Last Modified On : Mon Nov  8 10:18:00 2021
    13 // Update Count     : 17
     11// Last Modified By : Peter A. Buhr
     12// Last Modified On : Mon Jan 31 22:30:26 2022
     13// Update Count     : 28
    1414//
    1515
     
    1717#include <sstream>              // for ostringstream
    1818#include <list>                 // for list
     19using namespace std;
    1920
    2021#include "LabelGenerator.h"
    2122
    22 #include "AST/Attribute.hpp"
    23 #include "AST/Label.hpp"
    24 #include "AST/Stmt.hpp"
    2523#include "SynTree/Attribute.h"  // for Attribute
    2624#include "SynTree/Label.h"      // for Label, operator<<
     
    2826
    2927namespace ControlStruct {
    30 
    3128int LabelGenerator::current = 0;
    3229LabelGenerator * LabelGenerator::labelGenerator = nullptr;
    3330
    34         LabelGenerator * LabelGenerator::getGenerator() {
    35                 if ( LabelGenerator::labelGenerator == 0 )
    36                         LabelGenerator::labelGenerator = new LabelGenerator();
    37                 return labelGenerator;
    38         }
    39 
    40         Label LabelGenerator::newLabel( std::string suffix, Statement * stmt ) {
    41                 std::ostringstream os;
    42                 os << "__L" << current++ << "__" << suffix;
    43                 if ( stmt && ! stmt->get_labels().empty() ) {
    44                         os << "_" << stmt->get_labels().front() << "__";
    45                 } // if
    46                 std::string ret = os.str();
    47                 Label l( ret );
    48                 l.get_attributes().push_back( new Attribute("unused") );
    49                 return l;
    50         }
    51 
    52 ast::Label LabelGenerator::newLabel(
    53                 const std::string & suffix, const ast::Stmt * stmt ) {
    54         assert( stmt );
    55 
    56         std::ostringstream os;
    57         os << "__L" << current++ << "__" << suffix;
    58         if ( stmt && !stmt->labels.empty() ) {
    59                 os << "_" << stmt->labels.front() << "__";
    60         }
    61         ast::Label ret_label( stmt->location, os.str() );
    62         ret_label.attributes.push_back( new ast::Attribute( "unused" ) );
    63         return ret_label;
     31LabelGenerator * LabelGenerator::getGenerator() {
     32        if ( LabelGenerator::labelGenerator == 0 )
     33                LabelGenerator::labelGenerator = new LabelGenerator();
     34        return labelGenerator;
    6435}
    6536
     37Label LabelGenerator::newLabel( string suffix, Statement * stmt ) {
     38        ostringstream os;
     39        os << "__L_OLD" << current++ << "__" << suffix;
     40        if ( stmt && ! stmt->get_labels().empty() ) {
     41                os << "_" << stmt->get_labels().front() << "__";
     42        } // if
     43        string ret = os.str();
     44        Label l( ret );
     45        l.get_attributes().push_back( new Attribute( "unused" ) );
     46        return l;
     47}
    6648} // namespace ControlStruct
    6749
    6850// Local Variables: //
    69 // tab-width: 4 //
    7051// mode: c++ //
    71 // compile-command: "make install" //
    7252// End: //
  • TabularUnified src/ControlStruct/LabelGenerator.h

    r3e5db5b4 r34c32f0  
    99// Author           : Rodolfo G. Esteves
    1010// Created On       : Mon May 18 07:44:20 2015
    11 // Last Modified By : Andrew Beach
    12 // Last Modified On : Mon Nov  8 10:16:00 2021
    13 // Update Count     : 8
     11// Last Modified By : Peter A. Buhr
     12// Last Modified On : Mon Jan 31 22:30:10 2022
     13// Update Count     : 16
    1414//
    1515
     
    2121
    2222class Statement;
     23
    2324namespace ast {
    24         class Stmt;
    25         class Label;
     25class Stmt;
     26class Label;
    2627}
    2728
    2829namespace ControlStruct {
    29 
    3030class LabelGenerator {
    3131        static int current;
    3232        static LabelGenerator *labelGenerator;
    33 protected:
     33  protected:
    3434        LabelGenerator() {}
    35 public:
     35  public:
    3636        static LabelGenerator *getGenerator();
    3737        static Label newLabel(std::string suffix, Statement * stmt = nullptr);
    38         static ast::Label newLabel( const std::string&, const ast::Stmt * );
    39         static void reset() { current = 0; }
    40         static void rewind() { current--; }
    4138};
    42 
    4339} // namespace ControlStruct
    4440
  • TabularUnified src/ControlStruct/MultiLevelExit.cpp

    r3e5db5b4 r34c32f0  
    99// Author           : Andrew Beach
    1010// Created On       : Mon Nov  1 13:48:00 2021
    11 // Last Modified By : Andrew Beach
    12 // Last Modified On : Mon Nov  8 10:56:00 2021
    13 // Update Count     : 2
     11// Last Modified By : Peter A. Buhr
     12// Last Modified On : Mon Jan 31 22:35:08 2022
     13// Update Count     : 28
    1414//
    1515
     
    1818#include "AST/Pass.hpp"
    1919#include "AST/Stmt.hpp"
    20 #include "ControlStruct/LabelGenerator.h"
     20#include "LabelGeneratorNew.hpp"
    2121
    2222#include <set>
     23using namespace std;
     24using namespace ast;
    2325
    2426namespace ControlStruct {
    25 
    26 namespace {
    27 
    2827class Entry {
    29 public:
    30         const ast::Stmt * stmt;
    31 private:
     28  public:
     29        const Stmt * stmt;
     30  private:
    3231        // Organized like a manual ADT. Avoids creating a bunch of dead data.
    3332        struct Target {
    34                 ast::Label label;
     33                Label label;
    3534                bool used = false;
    36                 Target( const ast::Label & label ) : label( label ) {}
     35                Target( const Label & label ) : label( label ) {}
    3736                Target() : label( CodeLocation() ) {}
    3837        };
     
    4140
    4241        enum Kind {
    43                 ForStmt, WhileStmt, CompoundStmt, IfStmt, CaseStmt, SwitchStmt, TryStmt
     42                ForStmtK, WhileStmtK, CompoundStmtK, IfStmtK, CaseStmtK, SwitchStmtK, TryStmtK
    4443        } kind;
    4544
    4645        bool fallDefaultValid = true;
    4746
    48         static ast::Label & useTarget( Target & target ) {
     47        static Label & useTarget( Target & target ) {
    4948                target.used = true;
    5049                return target.label;
    5150        }
    5251
    53 public:
    54         Entry( const ast::ForStmt * stmt, ast::Label breakExit, ast::Label contExit ) :
    55                 stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( ForStmt ) {}
    56         Entry( const ast::WhileStmt * stmt, ast::Label breakExit, ast::Label contExit ) :
    57                 stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( WhileStmt ) {}
    58         Entry( const ast::CompoundStmt *stmt, ast::Label breakExit ) :
    59                 stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( CompoundStmt ) {}
    60         Entry( const ast::IfStmt *stmt, ast::Label breakExit ) :
    61                 stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( IfStmt ) {}
    62         Entry( const ast::CaseStmt *stmt, ast::Label fallExit ) :
    63                 stmt( stmt ), firstTarget( fallExit ), secondTarget(), kind( CaseStmt ) {}
    64         Entry( const ast::SwitchStmt *stmt, ast::Label breakExit, ast::Label fallDefaultExit ) :
    65                 stmt( stmt ), firstTarget( breakExit ), secondTarget( fallDefaultExit ), kind( SwitchStmt ) {}
    66         Entry( const ast::TryStmt *stmt, ast::Label breakExit ) :
    67                 stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( TryStmt ) {}
    68 
    69         bool isContTarget() const { return kind <= WhileStmt; }
    70         bool isBreakTarget() const { return CaseStmt != kind; }
    71         bool isFallTarget() const { return CaseStmt == kind; }
    72         bool isFallDefaultTarget() const { return SwitchStmt == kind; }
     52  public:
     53        Entry( const ForStmt * stmt, Label breakExit, Label contExit ) :
     54                stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( ForStmtK ) {}
     55        Entry( const WhileStmt * stmt, Label breakExit, Label contExit ) :
     56                stmt( stmt ), firstTarget( breakExit ), secondTarget( contExit ), kind( WhileStmtK ) {}
     57        Entry( const CompoundStmt *stmt, Label breakExit ) :
     58                stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( CompoundStmtK ) {}
     59        Entry( const IfStmt *stmt, Label breakExit ) :
     60                stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( IfStmtK ) {}
     61        Entry( const CaseStmt *stmt, Label fallExit ) :
     62                stmt( stmt ), firstTarget( fallExit ), secondTarget(), kind( CaseStmtK ) {}
     63        Entry( const SwitchStmt *stmt, Label breakExit, Label fallDefaultExit ) :
     64                stmt( stmt ), firstTarget( breakExit ), secondTarget( fallDefaultExit ), kind( SwitchStmtK ) {}
     65        Entry( const TryStmt *stmt, Label breakExit ) :
     66                stmt( stmt ), firstTarget( breakExit ), secondTarget(), kind( TryStmtK ) {}
     67
     68        bool isContTarget() const { return kind <= WhileStmtK; }
     69        bool isBreakTarget() const { return kind != CaseStmtK; }
     70        bool isFallTarget() const { return kind == CaseStmtK; }
     71        bool isFallDefaultTarget() const { return kind == SwitchStmtK; }
    7372
    7473        // These routines set a target as being "used" by a BranchStmt
    75         ast::Label useContExit() { assert( kind <= WhileStmt ); return useTarget(secondTarget); }
    76         ast::Label useBreakExit() { assert( CaseStmt != kind ); return useTarget(firstTarget); }
    77         ast::Label useFallExit() { assert( CaseStmt == kind );  return useTarget(firstTarget); }
    78         ast::Label useFallDefaultExit() { assert( SwitchStmt == kind ); return useTarget(secondTarget); }
     74        Label useContExit() { assert( kind <= WhileStmtK ); return useTarget(secondTarget); }
     75        Label useBreakExit() { assert( kind != CaseStmtK ); return useTarget(firstTarget); }
     76        Label useFallExit() { assert( kind == CaseStmtK );  return useTarget(firstTarget); }
     77        Label useFallDefaultExit() { assert( kind == SwitchStmtK ); return useTarget(secondTarget); }
    7978
    8079        // These routines check if a specific label for a statement is used by a BranchStmt
    81         bool isContUsed() const { assert( kind <= WhileStmt ); return secondTarget.used; }
    82         bool isBreakUsed() const { assert( CaseStmt != kind ); return firstTarget.used; }
    83         bool isFallUsed() const { assert( CaseStmt == kind ); return firstTarget.used; }
    84         bool isFallDefaultUsed() const { assert( SwitchStmt == kind ); return secondTarget.used; }
     80        bool isContUsed() const { assert( kind <= WhileStmtK ); return secondTarget.used; }
     81        bool isBreakUsed() const { assert( kind != CaseStmtK ); return firstTarget.used; }
     82        bool isFallUsed() const { assert( kind == CaseStmtK ); return firstTarget.used; }
     83        bool isFallDefaultUsed() const { assert( kind == SwitchStmtK ); return secondTarget.used; }
    8584        void seenDefault() { fallDefaultValid = false; }
    8685        bool isFallDefaultValid() const { return fallDefaultValid; }
    8786};
    8887
    89 // Helper predicates used in std::find_if calls (it doesn't take methods):
     88// Helper predicates used in find_if calls (it doesn't take methods):
    9089bool isBreakTarget( const Entry & entry ) {
    9190        return entry.isBreakTarget();
     
    105104
    106105struct MultiLevelExitCore final :
    107                 public ast::WithVisitorRef<MultiLevelExitCore>,
    108                 public ast::WithShortCircuiting, public ast::WithGuards {
     106        public WithVisitorRef<MultiLevelExitCore>,
     107        public WithShortCircuiting, public WithGuards {
    109108        MultiLevelExitCore( const LabelToStmt & lt );
    110109
    111         void previsit( const ast::FunctionDecl * );
    112 
    113         const ast::CompoundStmt * previsit( const ast::CompoundStmt * );
    114         const ast::BranchStmt * postvisit( const ast::BranchStmt * );
    115         void previsit( const ast::WhileStmt * );
    116         const ast::WhileStmt * postvisit( const ast::WhileStmt * );
    117         void previsit( const ast::ForStmt * );
    118         const ast::ForStmt * postvisit( const ast::ForStmt * );
    119         const ast::CaseStmt * previsit( const ast::CaseStmt * );
    120         void previsit( const ast::IfStmt * );
    121         const ast::IfStmt * postvisit( const ast::IfStmt * );
    122         void previsit( const ast::SwitchStmt * );
    123         const ast::SwitchStmt * postvisit( const ast::SwitchStmt * );
    124         void previsit( const ast::ReturnStmt * );
    125         void previsit( const ast::TryStmt * );
    126         void postvisit( const ast::TryStmt * );
    127         void previsit( const ast::FinallyStmt * );
    128 
    129         const ast::Stmt * mutateLoop( const ast::Stmt * body, Entry& );
     110        void previsit( const FunctionDecl * );
     111
     112        const CompoundStmt * previsit( const CompoundStmt * );
     113        const BranchStmt * postvisit( const BranchStmt * );
     114        void previsit( const WhileStmt * );
     115        const WhileStmt * postvisit( const WhileStmt * );
     116        void previsit( const ForStmt * );
     117        const ForStmt * postvisit( const ForStmt * );
     118        const CaseStmt * previsit( const CaseStmt * );
     119        void previsit( const IfStmt * );
     120        const IfStmt * postvisit( const IfStmt * );
     121        void previsit( const SwitchStmt * );
     122        const SwitchStmt * postvisit( const SwitchStmt * );
     123        void previsit( const ReturnStmt * );
     124        void previsit( const TryStmt * );
     125        void postvisit( const TryStmt * );
     126        void previsit( const FinallyStmt * );
     127
     128        const Stmt * mutateLoop( const Stmt * body, Entry& );
    130129
    131130        const LabelToStmt & target_table;
    132         std::set<ast::Label> fallthrough_labels;
    133         std::vector<Entry> enclosing_control_structures;
    134         ast::Label break_label;
     131        set<Label> fallthrough_labels;
     132        vector<Entry> enclosing_control_structures;
     133        Label break_label;
    135134        bool inFinally;
    136135
     
    140139        const LoopNode * posthandleLoopStmt( const LoopNode * loopStmt );
    141140
    142         std::list<ast::ptr<ast::Stmt>> fixBlock(
    143                 const std::list<ast::ptr<ast::Stmt>> & kids, bool caseClause );
     141        list<ptr<Stmt>> fixBlock(
     142                const list<ptr<Stmt>> & kids, bool caseClause );
    144143
    145144        template<typename UnaryPredicate>
    146145        auto findEnclosingControlStructure( UnaryPredicate pred ) {
    147                 return std::find_if( enclosing_control_structures.rbegin(),
    148                         enclosing_control_structures.rend(), pred );
     146                return find_if( enclosing_control_structures.rbegin(),
     147                                                enclosing_control_structures.rend(), pred );
    149148        }
    150149};
    151150
    152 ast::NullStmt * labelledNullStmt(
    153                 const CodeLocation & cl, const ast::Label & label ) {
    154         return new ast::NullStmt( cl, std::vector<ast::Label>{ label } );
     151NullStmt * labelledNullStmt(
     152        const CodeLocation & cl, const Label & label ) {
     153        return new NullStmt( cl, vector<Label>{ label } );
    155154}
    156155
     
    160159{}
    161160
    162 void MultiLevelExitCore::previsit( const ast::FunctionDecl * ) {
     161void MultiLevelExitCore::previsit( const FunctionDecl * ) {
    163162        visit_children = false;
    164163}
    165164
    166 const ast::CompoundStmt * MultiLevelExitCore::previsit(
    167                 const ast::CompoundStmt * stmt ) {
     165const CompoundStmt * MultiLevelExitCore::previsit(
     166        const CompoundStmt * stmt ) {
    168167        visit_children = false;
    169168
     
    171170        bool isLabeled = !stmt->labels.empty();
    172171        if ( isLabeled ) {
    173                 ast::Label breakLabel = LabelGenerator::newLabel( "blockBreak", stmt );
     172                Label breakLabel = newLabel( "blockBreak", stmt );
    174173                enclosing_control_structures.emplace_back( stmt, breakLabel );
    175174                GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
    176175        }
    177176
    178         auto mutStmt = ast::mutate( stmt );
     177        auto mutStmt = mutate( stmt );
    179178        // A child statement may set the break label.
    180         mutStmt->kids = std::move( fixBlock( stmt->kids, false ) );
     179        mutStmt->kids = move( fixBlock( stmt->kids, false ) );
    181180
    182181        if ( isLabeled ) {
     
    191190
    192191size_t getUnusedIndex(
    193                 const ast::Stmt * stmt, const ast::Label & originalTarget ) {
     192        const Stmt * stmt, const Label & originalTarget ) {
    194193        const size_t size = stmt->labels.size();
    195194
    196         // If the label is empty, we can skip adding the unused attribute:
    197         if ( originalTarget.empty() ) return size;
     195        // If the label is empty, do not add unused attribute.
     196  if ( originalTarget.empty() ) return size;
    198197
    199198        // Search for a label that matches the originalTarget.
    200199        for ( size_t i = 0 ; i < size ; ++i ) {
    201                 const ast::Label & label = stmt->labels[i];
     200                const Label & label = stmt->labels[i];
    202201                if ( label == originalTarget ) {
    203                         for ( const ast::Attribute * attr : label.attributes ) {
     202                        for ( const Attribute * attr : label.attributes ) {
    204203                                if ( attr->name == "unused" ) return size;
    205204                        }
     
    208207        }
    209208        assertf( false, "Could not find label '%s' on statement %s",
    210                 originalTarget.name.c_str(), toString( stmt ).c_str() );
    211 }
    212 
    213 const ast::Stmt * addUnused(
    214                 const ast::Stmt * stmt, const ast::Label & originalTarget ) {
     209                         originalTarget.name.c_str(), toString( stmt ).c_str() );
     210}
     211
     212const Stmt * addUnused(
     213        const Stmt * stmt, const Label & originalTarget ) {
    215214        size_t i = getUnusedIndex( stmt, originalTarget );
    216215        if ( i == stmt->labels.size() ) {
    217216                return stmt;
    218217        }
    219         ast::Stmt * mutStmt = ast::mutate( stmt );
    220         mutStmt->labels[i].attributes.push_back( new ast::Attribute( "unused" ) );
     218        Stmt * mutStmt = mutate( stmt );
     219        mutStmt->labels[i].attributes.push_back( new Attribute( "unused" ) );
    221220        return mutStmt;
    222221}
     
    224223// This routine updates targets on enclosing control structures to indicate which
    225224//     label is used by the BranchStmt that is passed
    226 const ast::BranchStmt * MultiLevelExitCore::postvisit( const ast::BranchStmt * stmt ) {
    227         std::vector<Entry>::reverse_iterator targetEntry =
     225const BranchStmt * MultiLevelExitCore::postvisit( const BranchStmt * stmt ) {
     226        vector<Entry>::reverse_iterator targetEntry =
    228227                enclosing_control_structures.rend();
    229228
    230229        // Labels on different stmts require different approaches to access
    231230        switch ( stmt->kind ) {
    232         case ast::BranchStmt::Goto:
     231          case BranchStmt::Goto:
    233232                return stmt;
    234         case ast::BranchStmt::Continue:
    235         case ast::BranchStmt::Break: {
    236                 bool isContinue = stmt->kind == ast::BranchStmt::Continue;
    237                 // Handle unlabeled break and continue.
    238                 if ( stmt->target.empty() ) {
    239                         if ( isContinue ) {
    240                                 targetEntry = findEnclosingControlStructure( isContinueTarget );
    241                         } else {
    242                                 if ( enclosing_control_structures.empty() ) {
    243                                         SemanticError( stmt->location,
    244                                                 "'break' outside a loop, 'switch', or labelled block" );
    245                                 }
    246                                 targetEntry = findEnclosingControlStructure( isBreakTarget );
    247                         }
    248                 // Handle labeled break and continue.
    249                 } else {
    250                         // Lookup label in table to find attached control structure.
    251                         targetEntry = findEnclosingControlStructure(
    252                                 [ targetStmt = target_table.at(stmt->target) ](auto entry){
    253                                         return entry.stmt == targetStmt;
    254                                 } );
    255                 }
    256                 // Ensure that selected target is valid.
    257                 if ( targetEntry == enclosing_control_structures.rend() || ( isContinue && !isContinueTarget( *targetEntry ) ) ) {
    258                         SemanticError(
    259                                 stmt->location,
    260                                 toString( (isContinue ? "'continue'" : "'break'"),
    261                                         " target must be an enclosing ",
    262                                         (isContinue ? "loop: " : "control structure: "),
    263                                         stmt->originalTarget ) );
    264                 }
    265                 break;
    266         }
    267         // handle fallthrough in case/switch stmts
    268         case ast::BranchStmt::FallThrough: {
    269                 targetEntry = findEnclosingControlStructure( isFallthroughTarget );
    270                 // Check that target is valid.
    271                 if ( targetEntry == enclosing_control_structures.rend() ) {
    272                         SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
    273                 }
    274                 if ( !stmt->target.empty() ) {
    275                         // Labelled fallthrough: target must be a valid fallthough label.
    276                         if ( !fallthrough_labels.count( stmt->target ) ) {
    277                                 SemanticError( stmt->location, toString( "'fallthrough' target must be a later case statement: ", stmt->originalTarget ) );
    278                         }
    279                         return new ast::BranchStmt(
    280                                 stmt->location, ast::BranchStmt::Goto, stmt->originalTarget );
    281                 }
    282                 break;
    283         }
    284         case ast::BranchStmt::FallThroughDefault: {
    285                 targetEntry = findEnclosingControlStructure( isFallthroughDefaultTarget );
    286 
    287                 // Check that this is in a switch or choose statement.
    288                 if ( targetEntry == enclosing_control_structures.rend() ) {
    289                         SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
    290                 }
    291 
    292                 // Check that the switch or choose has a default clause.
    293                 auto switchStmt = strict_dynamic_cast< const ast::SwitchStmt * >(
    294                         targetEntry->stmt );
    295                 bool foundDefault = false;
    296                 for ( auto subStmt : switchStmt->stmts ) {
    297                         const ast::CaseStmt * caseStmt = subStmt.strict_as<ast::CaseStmt>();
    298                         if ( caseStmt->isDefault() ) {
    299                                 foundDefault = true;
    300                                 break;
    301                         }
    302                 }
    303                 if ( !foundDefault ) {
    304                         SemanticError( stmt->location, "'fallthrough default' must be enclosed in a 'switch' or 'choose' control structure with a 'default' clause" );
    305                 }
    306                 break;
    307         }
    308         default:
     233          case BranchStmt::Continue:
     234          case BranchStmt::Break: {
     235                  bool isContinue = stmt->kind == BranchStmt::Continue;
     236                  // Handle unlabeled break and continue.
     237                  if ( stmt->target.empty() ) {
     238                          if ( isContinue ) {
     239                                  targetEntry = findEnclosingControlStructure( isContinueTarget );
     240                          } else {
     241                                  if ( enclosing_control_structures.empty() ) {
     242                                          SemanticError( stmt->location,
     243                                                                         "'break' outside a loop, 'switch', or labelled block" );
     244                                  }
     245                                  targetEntry = findEnclosingControlStructure( isBreakTarget );
     246                          }
     247                          // Handle labeled break and continue.
     248                  } else {
     249                          // Lookup label in table to find attached control structure.
     250                          targetEntry = findEnclosingControlStructure(
     251                                  [ targetStmt = target_table.at(stmt->target) ](auto entry){
     252                                          return entry.stmt == targetStmt;
     253                                  } );
     254                  }
     255                  // Ensure that selected target is valid.
     256                  if ( targetEntry == enclosing_control_structures.rend() || ( isContinue && !isContinueTarget( *targetEntry ) ) ) {
     257                          SemanticError( stmt->location, toString( (isContinue ? "'continue'" : "'break'"),
     258                                                        " target must be an enclosing ", (isContinue ? "loop: " : "control structure: "),
     259                                                        stmt->originalTarget ) );
     260                  }
     261                  break;
     262          }
     263          // handle fallthrough in case/switch stmts
     264          case BranchStmt::FallThrough: {
     265                  targetEntry = findEnclosingControlStructure( isFallthroughTarget );
     266                  // Check that target is valid.
     267                  if ( targetEntry == enclosing_control_structures.rend() ) {
     268                          SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
     269                  }
     270                  if ( !stmt->target.empty() ) {
     271                          // Labelled fallthrough: target must be a valid fallthough label.
     272                          if ( !fallthrough_labels.count( stmt->target ) ) {
     273                                  SemanticError( stmt->location, toString( "'fallthrough' target must be a later case statement: ",
     274                                                                                                                   stmt->originalTarget ) );
     275                          }
     276                          return new BranchStmt(
     277                                  stmt->location, BranchStmt::Goto, stmt->originalTarget );
     278                  }
     279                  break;
     280          }
     281          case BranchStmt::FallThroughDefault: {
     282                  targetEntry = findEnclosingControlStructure( isFallthroughDefaultTarget );
     283
     284                  // Check if in switch or choose statement.
     285                  if ( targetEntry == enclosing_control_structures.rend() ) {
     286                          SemanticError( stmt->location, "'fallthrough' must be enclosed in a 'switch' or 'choose'" );
     287                  }
     288
     289                  // Check if switch or choose has default clause.
     290                  auto switchStmt = strict_dynamic_cast< const SwitchStmt * >( targetEntry->stmt );
     291                  bool foundDefault = false;
     292                  for ( auto subStmt : switchStmt->stmts ) {
     293                          const CaseStmt * caseStmt = subStmt.strict_as<CaseStmt>();
     294                          if ( caseStmt->isDefault() ) {
     295                                  foundDefault = true;
     296                                  break;
     297                          }
     298                  }
     299                  if ( ! foundDefault ) {
     300                          SemanticError( stmt->location, "'fallthrough default' must be enclosed in a 'switch' or 'choose'"
     301                                                         "control structure with a 'default' clause" );
     302                  }
     303                  break;
     304          }
     305          default:
    309306                assert( false );
    310307        }
    311308
    312309        // Branch error checks: get the appropriate label name:
    313         // (This label will always be replaced.)
    314         ast::Label exitLabel( CodeLocation(), "" );
     310        // (This label is always replaced.)
     311        Label exitLabel( CodeLocation(), "" );
    315312        switch ( stmt->kind ) {
    316         case ast::BranchStmt::Break:
     313          case BranchStmt::Break:
    317314                assert( !targetEntry->useBreakExit().empty() );
    318315                exitLabel = targetEntry->useBreakExit();
    319316                break;
    320         case ast::BranchStmt::Continue:
     317          case BranchStmt::Continue:
    321318                assert( !targetEntry->useContExit().empty() );
    322319                exitLabel = targetEntry->useContExit();
    323320                break;
    324         case ast::BranchStmt::FallThrough:
     321          case BranchStmt::FallThrough:
    325322                assert( !targetEntry->useFallExit().empty() );
    326323                exitLabel = targetEntry->useFallExit();
    327324                break;
    328         case ast::BranchStmt::FallThroughDefault:
     325          case BranchStmt::FallThroughDefault:
    329326                assert( !targetEntry->useFallDefaultExit().empty() );
    330327                exitLabel = targetEntry->useFallDefaultExit();
    331328                // Check that fallthrough default comes before the default clause.
    332329                if ( !targetEntry->isFallDefaultValid() ) {
    333                         SemanticError( stmt->location,
    334                                 "'fallthrough default' must precede the 'default' clause" );
     330                        SemanticError( stmt->location, "'fallthrough default' must precede the 'default' clause" );
    335331                }
    336332                break;
    337         default:
     333          default:
    338334                assert(0);
    339335        }
     
    342338        targetEntry->stmt = addUnused( targetEntry->stmt, stmt->originalTarget );
    343339
    344         // Replace this with a goto to make later passes more uniform.
    345         return new ast::BranchStmt( stmt->location, ast::BranchStmt::Goto, exitLabel );
    346 }
    347 
    348 void MultiLevelExitCore::previsit( const ast::WhileStmt * stmt ) {
     340        // Replace with goto to make later passes more uniform.
     341        return new BranchStmt( stmt->location, BranchStmt::Goto, exitLabel );
     342}
     343
     344void MultiLevelExitCore::previsit( const WhileStmt * stmt ) {
    349345        return prehandleLoopStmt( stmt );
    350346}
    351347
    352 const ast::WhileStmt * MultiLevelExitCore::postvisit( const ast::WhileStmt * stmt ) {
     348const WhileStmt * MultiLevelExitCore::postvisit( const WhileStmt * stmt ) {
    353349        return posthandleLoopStmt( stmt );
    354350}
    355351
    356 void MultiLevelExitCore::previsit( const ast::ForStmt * stmt ) {
     352void MultiLevelExitCore::previsit( const ForStmt * stmt ) {
    357353        return prehandleLoopStmt( stmt );
    358354}
    359355
    360 const ast::ForStmt * MultiLevelExitCore::postvisit( const ast::ForStmt * stmt ) {
     356const ForStmt * MultiLevelExitCore::postvisit( const ForStmt * stmt ) {
    361357        return posthandleLoopStmt( stmt );
    362358}
     
    364360// Mimic what the built-in push_front would do anyways. It is O(n).
    365361void push_front(
    366                 std::vector<ast::ptr<ast::Stmt>> & vec, const ast::Stmt * element ) {
     362        vector<ptr<Stmt>> & vec, const Stmt * element ) {
    367363        vec.emplace_back( nullptr );
    368364        for ( size_t i = vec.size() - 1 ; 0 < i ; --i ) {
    369                 vec[ i ] = std::move( vec[ i - 1 ] );
     365                vec[ i ] = move( vec[ i - 1 ] );
    370366        }
    371367        vec[ 0 ] = element;
    372368}
    373369
    374 const ast::CaseStmt * MultiLevelExitCore::previsit( const ast::CaseStmt * stmt ) {
     370const CaseStmt * MultiLevelExitCore::previsit( const CaseStmt * stmt ) {
    375371        visit_children = false;
    376372
    377         // If it is the default, mark the default as seen.
     373        // If default, mark seen.
    378374        if ( stmt->isDefault() ) {
    379375                assert( !enclosing_control_structures.empty() );
     
    382378
    383379        // The cond may not exist, but if it does update it now.
    384         visitor->maybe_accept( stmt, &ast::CaseStmt::cond );
     380        visitor->maybe_accept( stmt, &CaseStmt::cond );
    385381
    386382        // Just save the mutated node for simplicity.
    387         ast::CaseStmt * mutStmt = ast::mutate( stmt );
    388 
    389         ast::Label fallLabel = LabelGenerator::newLabel( "fallThrough", stmt );
    390         if ( !mutStmt->stmts.empty() ) {
     383        CaseStmt * mutStmt = mutate( stmt );
     384
     385        Label fallLabel = newLabel( "fallThrough", stmt );
     386        if ( ! mutStmt->stmts.empty() ) {
    391387                // Ensure that the stack isn't corrupted by exceptions in fixBlock.
    392388                auto guard = makeFuncGuard(
    393389                        [&](){ enclosing_control_structures.emplace_back( mutStmt, fallLabel ); },
    394390                        [this](){ enclosing_control_structures.pop_back(); }
    395                 );
     391                        );
    396392
    397393                // These should already be in a block.
    398                 auto block = ast::mutate( mutStmt->stmts.front().strict_as<ast::CompoundStmt>() );
     394                auto block = mutate( mutStmt->stmts.front().strict_as<CompoundStmt>() );
    399395                block->kids = fixBlock( block->kids, true );
    400396
    401397                // Add fallthrough label if necessary.
    402                 assert( !enclosing_control_structures.empty() );
     398                assert( ! enclosing_control_structures.empty() );
    403399                Entry & entry = enclosing_control_structures.back();
    404400                if ( entry.isFallUsed() ) {
     
    407403                }
    408404        }
    409         assert( !enclosing_control_structures.empty() );
     405        assert( ! enclosing_control_structures.empty() );
    410406        Entry & entry = enclosing_control_structures.back();
    411         assertf( dynamic_cast< const ast::SwitchStmt * >( entry.stmt ),
    412                 "Control structure enclosing a case clause must be a switch, but is: %s",
    413                 toString( entry.stmt ).c_str() );
     407        assertf( dynamic_cast< const SwitchStmt * >( entry.stmt ),
     408                         "Control structure enclosing a case clause must be a switch, but is: %s",
     409                         toString( entry.stmt ).c_str() );
    414410        if ( mutStmt->isDefault() ) {
    415411                if ( entry.isFallDefaultUsed() ) {
    416412                        // Add fallthrough default label if necessary.
    417413                        push_front( mutStmt->stmts, labelledNullStmt(
    418                                 stmt->location, entry.useFallDefaultExit()
    419                         ) );
     414                                                        stmt->location, entry.useFallDefaultExit()
     415                                                        ) );
    420416                }
    421417        }
     
    423419}
    424420
    425 void MultiLevelExitCore::previsit( const ast::IfStmt * stmt ) {
     421void MultiLevelExitCore::previsit( const IfStmt * stmt ) {
    426422        bool labeledBlock = !stmt->labels.empty();
    427423        if ( labeledBlock ) {
    428                 ast::Label breakLabel = LabelGenerator::newLabel( "blockBreak", stmt );
     424                Label breakLabel = newLabel( "blockBreak", stmt );
    429425                enclosing_control_structures.emplace_back( stmt, breakLabel );
    430426                GuardAction( [this](){ enclosing_control_structures.pop_back(); } );
     
    432428}
    433429
    434 const ast::IfStmt * MultiLevelExitCore::postvisit( const ast::IfStmt * stmt ) {
     430const IfStmt * MultiLevelExitCore::postvisit( const IfStmt * stmt ) {
    435431        bool labeledBlock = !stmt->labels.empty();
    436432        if ( labeledBlock ) {
     
    443439}
    444440
    445 bool isDefaultCase( const ast::ptr<ast::Stmt> & stmt ) {
    446         const ast::CaseStmt * caseStmt = stmt.strict_as<ast::CaseStmt>();
     441bool isDefaultCase( const ptr<Stmt> & stmt ) {
     442        const CaseStmt * caseStmt = stmt.strict_as<CaseStmt>();
    447443        return caseStmt->isDefault();
    448444}
    449445
    450 void MultiLevelExitCore::previsit( const ast::SwitchStmt * stmt ) {
    451         ast::Label label = LabelGenerator::newLabel( "switchBreak", stmt );
    452         auto it = std::find_if( stmt->stmts.rbegin(), stmt->stmts.rend(), isDefaultCase );
    453 
    454         const ast::CaseStmt * defaultCase = it != stmt->stmts.rend()
    455                 ? (it)->strict_as<ast::CaseStmt>() : nullptr;
    456         ast::Label defaultLabel = defaultCase
    457                 ? LabelGenerator::newLabel( "fallThroughDefault", defaultCase )
    458                 : ast::Label( stmt->location, "" );
     446void MultiLevelExitCore::previsit( const SwitchStmt * stmt ) {
     447        Label label = newLabel( "switchBreak", stmt );
     448        auto it = find_if( stmt->stmts.rbegin(), stmt->stmts.rend(), isDefaultCase );
     449
     450        const CaseStmt * defaultCase = it != stmt->stmts.rend()
     451                ? (it)->strict_as<CaseStmt>() : nullptr;
     452        Label defaultLabel = defaultCase
     453                ? newLabel( "fallThroughDefault", defaultCase )
     454                : Label( stmt->location, "" );
    459455        enclosing_control_structures.emplace_back( stmt, label, defaultLabel );
    460456        GuardAction( [this]() { enclosing_control_structures.pop_back(); } );
    461457
    462458        // Collect valid labels for fallthrough. It starts with all labels at
    463         // this level, then removed as we see them in traversal.
    464         for ( const ast::Stmt * stmt : stmt->stmts ) {
    465                 auto * caseStmt = strict_dynamic_cast< const ast::CaseStmt * >( stmt );
     459        // this level, then remove as each is seen during traversal.
     460        for ( const Stmt * stmt : stmt->stmts ) {
     461                auto * caseStmt = strict_dynamic_cast< const CaseStmt * >( stmt );
    466462                if ( caseStmt->stmts.empty() ) continue;
    467                 auto block = caseStmt->stmts.front().strict_as<ast::CompoundStmt>();
    468                 for ( const ast::Stmt * stmt : block->kids ) {
    469                         for ( const ast::Label & l : stmt->labels ) {
     463                auto block = caseStmt->stmts.front().strict_as<CompoundStmt>();
     464                for ( const Stmt * stmt : block->kids ) {
     465                        for ( const Label & l : stmt->labels ) {
    470466                                fallthrough_labels.insert( l );
    471467                        }
     
    474470}
    475471
    476 const ast::SwitchStmt * MultiLevelExitCore::postvisit( const ast::SwitchStmt * stmt ) {
     472const SwitchStmt * MultiLevelExitCore::postvisit( const SwitchStmt * stmt ) {
    477473        assert( !enclosing_control_structures.empty() );
    478474        Entry & entry = enclosing_control_structures.back();
    479475        assert( entry.stmt == stmt );
    480476
    481         // Only run if we need to generate the break label.
     477        // Only run to generate the break label.
    482478        if ( entry.isBreakUsed() ) {
    483479                // To keep the switch statements uniform (all direct children of a
    484480                // SwitchStmt should be CastStmts), append the exit label and break
    485481                // to the last case, create a default case is there are no cases.
    486                 ast::SwitchStmt * mutStmt = ast::mutate( stmt );
     482                SwitchStmt * mutStmt = mutate( stmt );
    487483                if ( mutStmt->stmts.empty() ) {
    488                         mutStmt->stmts.push_back( new ast::CaseStmt(
    489                                 mutStmt->location, nullptr, {} ));
    490                 }
    491 
    492                 auto caseStmt = mutStmt->stmts.back().strict_as<ast::CaseStmt>();
    493                 auto mutCase = ast::mutate( caseStmt );
     484                        mutStmt->stmts.push_back( new CaseStmt(
     485                                                                                  mutStmt->location, nullptr, {} ));
     486                }
     487
     488                auto caseStmt = mutStmt->stmts.back().strict_as<CaseStmt>();
     489                auto mutCase = mutate( caseStmt );
    494490                mutStmt->stmts.back() = mutCase;
    495491
    496                 ast::Label label( mutCase->location, "breakLabel" );
    497                 auto branch = new ast::BranchStmt( mutCase->location, ast::BranchStmt::Break, label );
     492                Label label( mutCase->location, "breakLabel" );
     493                auto branch = new BranchStmt( mutCase->location, BranchStmt::Break, label );
    498494                branch->labels.push_back( entry.useBreakExit() );
    499495                mutCase->stmts.push_back( branch );
     
    504500}
    505501
    506 void MultiLevelExitCore::previsit( const ast::ReturnStmt * stmt ) {
     502void MultiLevelExitCore::previsit( const ReturnStmt * stmt ) {
    507503        if ( inFinally ) {
    508504                SemanticError( stmt->location, "'return' may not appear in a finally clause" );
     
    510506}
    511507
    512 void MultiLevelExitCore::previsit( const ast::TryStmt * stmt ) {
     508void MultiLevelExitCore::previsit( const TryStmt * stmt ) {
    513509        bool isLabeled = !stmt->labels.empty();
    514510        if ( isLabeled ) {
    515                 ast::Label breakLabel = LabelGenerator::newLabel( "blockBreak", stmt );
     511                Label breakLabel = newLabel( "blockBreak", stmt );
    516512                enclosing_control_structures.emplace_back( stmt, breakLabel );
    517513                GuardAction([this](){ enclosing_control_structures.pop_back(); } );
     
    519515}
    520516
    521 void MultiLevelExitCore::postvisit( const ast::TryStmt * stmt ) {
     517void MultiLevelExitCore::postvisit( const TryStmt * stmt ) {
    522518        bool isLabeled = !stmt->labels.empty();
    523519        if ( isLabeled ) {
     
    529525}
    530526
    531 void MultiLevelExitCore::previsit( const ast::FinallyStmt * ) {
    532         GuardAction([this, old = std::move(enclosing_control_structures)](){
    533                 enclosing_control_structures = std::move(old);
    534         });
    535         enclosing_control_structures = std::vector<Entry>();
     527void MultiLevelExitCore::previsit( const FinallyStmt * ) {
     528        GuardAction([this, old = move(enclosing_control_structures)](){
     529                                        enclosing_control_structures = move(old);
     530                                });
     531        enclosing_control_structures = vector<Entry>();
    536532        GuardValue( inFinally ) = true;
    537533}
    538534
    539 const ast::Stmt * MultiLevelExitCore::mutateLoop(
    540                 const ast::Stmt * body, Entry & entry ) {
     535const Stmt * MultiLevelExitCore::mutateLoop(
     536        const Stmt * body, Entry & entry ) {
    541537        if ( entry.isBreakUsed() ) {
    542538                break_label = entry.useBreakExit();
     
    545541        // if continue is used insert a continue label into the back of the body of the loop
    546542        if ( entry.isContUsed() ) {
    547                 ast::CompoundStmt * new_body = new ast::CompoundStmt( body->location );
     543                CompoundStmt * new_body = new CompoundStmt( body->location );
    548544                // {}
    549545                new_body->kids.push_back( body );
     
    567563        // Remember is loop before going onto mutate the body.
    568564        // The labels will be folded in if they are used.
    569         ast::Label breakLabel = LabelGenerator::newLabel( "loopBreak", loopStmt );
    570         ast::Label contLabel = LabelGenerator::newLabel( "loopContinue", loopStmt );
     565        Label breakLabel = newLabel( "loopBreak", loopStmt );
     566        Label contLabel = newLabel( "loopContinue", loopStmt );
    571567        enclosing_control_structures.emplace_back( loopStmt, breakLabel, contLabel );
    572568        // labels are added temporarily to see if they are used and then added permanently in postvisit if ther are used
     
    583579        assert( entry.stmt == loopStmt );
    584580
    585         // Now we check if the labels are used and add them if so.
    586         return ast::mutate_field(
     581        // Now check if the labels are used and add them if so.
     582        return mutate_field(
    587583                loopStmt, &LoopNode::body, mutateLoop( loopStmt->body, entry ) );
    588584        // this call to mutate_field compares loopStmt->body and the result of mutateLoop
     
    591587}
    592588
    593 std::list<ast::ptr<ast::Stmt>> MultiLevelExitCore::fixBlock(
    594                 const std::list<ast::ptr<ast::Stmt>> & kids, bool is_case_clause ) {
    595         // Unfortunately we can't use the automatic error collection.
     589list<ptr<Stmt>> MultiLevelExitCore::fixBlock(
     590        const list<ptr<Stmt>> & kids, bool is_case_clause ) {
     591        // Unfortunately cannot use automatic error collection.
    596592        SemanticErrorException errors;
    597593
    598         std::list<ast::ptr<ast::Stmt>> ret;
     594        list<ptr<Stmt>> ret;
    599595
    600596        // Manually visit each child.
    601         for ( const ast::ptr<ast::Stmt> & kid : kids ) {
     597        for ( const ptr<Stmt> & kid : kids ) {
    602598                if ( is_case_clause ) {
    603599                        // Once a label is seen, it's no longer a valid for fallthrough.
    604                         for ( const ast::Label & l : kid->labels ) {
     600                        for ( const Label & l : kid->labels ) {
    605601                                fallthrough_labels.erase( l );
    606602                        }
     
    616612                        ret.push_back(
    617613                                labelledNullStmt( ret.back()->location, break_label ) );
    618                         break_label = ast::Label( CodeLocation(), "" );
     614                        break_label = Label( CodeLocation(), "" );
    619615                }
    620616        }
     
    626622}
    627623
    628 } // namespace
    629 
    630 const ast::CompoundStmt * multiLevelExitUpdate(
    631         const ast::CompoundStmt * stmt,
    632                 const LabelToStmt & labelTable ) {
     624const CompoundStmt * multiLevelExitUpdate(
     625        const CompoundStmt * stmt,
     626        const LabelToStmt & labelTable ) {
    633627        // Must start in the body, so FunctionDecls can be a stopping point.
    634         ast::Pass<MultiLevelExitCore> visitor( labelTable );
    635         const ast::CompoundStmt * ret = stmt->accept( visitor );
     628        Pass<MultiLevelExitCore> visitor( labelTable );
     629        const CompoundStmt * ret = stmt->accept( visitor );
    636630        return ret;
    637631}
    638 
    639632} // namespace ControlStruct
    640633
  • TabularUnified src/ControlStruct/MultiLevelExit.hpp

    r3e5db5b4 r34c32f0  
    99// Author           : Andrew Beach
    1010// Created On       : Mon Nov  1 13:49:00 2021
    11 // Last Modified By : Andrew Beach
    12 // Last Modified On : Mon Nov  8 10:53:00 2021
    13 // Update Count     : 3
     11// Last Modified By : Peter A. Buhr
     12// Last Modified On : Mon Jan 31 22:34:06 2022
     13// Update Count     : 6
    1414//
    1515
     
    1919
    2020namespace ast {
    21         class CompoundStmt;
    22         class Label;
    23         class Stmt;
     21class CompoundStmt;
     22class Label;
     23class Stmt;
    2424}
    2525
    2626namespace ControlStruct {
    27 
    2827using LabelToStmt = std::map<ast::Label, const ast::Stmt *>;
    2928
    30 /// Mutate a function body to handle multi-level exits.
    31 const ast::CompoundStmt * multiLevelExitUpdate(
    32         const ast::CompoundStmt *, const LabelToStmt & );
    33 
     29// Mutate a function body to handle multi-level exits.
     30const ast::CompoundStmt * multiLevelExitUpdate( const ast::CompoundStmt *, const LabelToStmt & );
    3431}
    3532
  • TabularUnified src/ControlStruct/module.mk

    r3e5db5b4 r34c32f0  
    1010## Author           : Richard C. Bilson
    1111## Created On       : Mon Jun  1 17:49:17 2015
    12 ## Last Modified By : Henry Xue
    13 ## Last Modified On : Tue Jul 20 04:10:50 2021
    14 ## Update Count     : 5
     12## Last Modified By : Peter A. Buhr
     13## Last Modified On : Sat Jan 29 12:04:19 2022
     14## Update Count     : 7
    1515###############################################################################
    1616
     
    2828        ControlStruct/LabelGenerator.cc \
    2929        ControlStruct/LabelGenerator.h \
     30        ControlStruct/LabelGeneratorNew.cpp \
     31        ControlStruct/LabelGeneratorNew.hpp \
    3032        ControlStruct/MLEMutator.cc \
    3133        ControlStruct/MLEMutator.h \
Note: See TracChangeset for help on using the changeset viewer.