Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/InitTweak/FixInit.cc

    r5fe35d6 r9d06142  
    5454#include "SynTree/Type.h"              // for Type, Type::StorageClasses
    5555#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution, operator<<
     56#include "SynTree/VarExprReplacer.h"   // for VarExprReplacer
    5657#include "SynTree/Visitor.h"           // for acceptAll, maybeAccept
    5758
     
    158159                        using Parent::previsit;
    159160
    160                         void previsit( ObjectDecl * objDecl );
    161161                        void previsit( FunctionDecl * funcDecl );
    162162
    163                         void previsit( CompoundStmt * compoundStmt );
    164                         void postvisit( CompoundStmt * compoundStmt );
    165                         void previsit( ReturnStmt * returnStmt );
    166163                        void previsit( BranchStmt * stmt );
    167164                private:
     
    203200                        static void generate( std::list< Declaration * > & translationUnit );
    204201
     202                        void previsit( StructDecl * structDecl );
     203
    205204                        void previsit( FunctionDecl * funcDecl );
    206205                        void postvisit( FunctionDecl * funcDecl );
     
    220219                        bool isCtor = false; // true if current function is a constructor
    221220                        StructDecl * structDecl = nullptr;
     221
     222                        // special built-in functions necessary for this to work
     223                        StructDecl * dtorStruct = nullptr;
     224                        FunctionDecl * dtorStructDestroy = nullptr;
    222225                };
    223226
     
    650653                }
    651654
     655                DeclarationWithType * getDtorFunc( ObjectDecl * objDecl, Statement * input, std::list< Statement * > & stmtsToAdd ) {
     656                        // unwrap implicit statement wrapper
     657                        Statement * dtor = input;
     658                        if ( ImplicitCtorDtorStmt * implicit = dynamic_cast< ImplicitCtorDtorStmt * >( input ) ) {
     659                                // dtor = implicit->callStmt;
     660                                // implicit->callStmt = nullptr;
     661                        }
     662                        assert( dtor );
     663                        std::list< Expression * > matches;
     664                        collectCtorDtorCalls( dtor, matches );
     665
     666                        if ( dynamic_cast< ExprStmt * >( dtor ) ) {
     667                                // only one destructor call in the expression
     668                                if ( matches.size() == 1 ) {
     669                                        DeclarationWithType * func = getFunction( matches.front() );
     670                                        assertf( func, "getFunction failed to find function in %s", toString( matches.front() ).c_str() );
     671
     672                                        // cleanup argument must be a function, not an object (including function pointer)
     673                                        if ( FunctionDecl * dtorFunc = dynamic_cast< FunctionDecl * > ( func ) ) {
     674                                                if ( dtorFunc->type->forall.empty() ) {
     675                                                        // simple case where the destructor is a monomorphic function call - can simply
     676                                                        // use that function as the cleanup function.
     677                                                        delete dtor;
     678                                                        return func;
     679                                                }
     680                                        }
     681                                }
     682                        }
     683
     684                        // otherwise the cleanup is more complicated - need to build a single argument cleanup function that
     685                        // wraps the more complicated code.
     686                        static UniqueName dtorNamer( "__cleanup_dtor" );
     687                        FunctionDecl * dtorFunc = FunctionDecl::newFunction( dtorNamer.newName(), SymTab::genDefaultType( objDecl->type->stripReferences(), false ), new CompoundStmt( noLabels ) );
     688                        stmtsToAdd.push_back( new DeclStmt( noLabels, dtorFunc ) );
     689
     690                        // the original code contains uses of objDecl - replace them with the newly generated 'this' parameter.
     691                        ObjectDecl * thisParam = getParamThis( dtorFunc->type );
     692                        Expression * replacement = new VariableExpr( thisParam );
     693
     694                        Type * base = replacement->result->stripReferences();
     695                        if ( dynamic_cast< ArrayType * >( base ) || dynamic_cast< TupleType * > ( base ) ) {
     696                                // need to cast away reference for array types, since the destructor is generated without the reference type,
     697                                // and for tuple types since tuple indexing does not work directly on a reference
     698                                replacement = new CastExpr( replacement, base->clone() );
     699                        }
     700                        VarExprReplacer::replace( dtor, { std::make_pair( objDecl, replacement ) } );
     701                        dtorFunc->statements->push_back( dtor );
     702
     703                        return dtorFunc;
     704                }
     705
    652706                DeclarationWithType * FixInit::postmutate( ObjectDecl *objDecl ) {
    653707                        // since this removes the init field from objDecl, it must occur after children are mutated (i.e. postmutate)
     
    762816                                                        ctorInit->ctor = nullptr;
    763817                                                }
     818
     819                                                Statement * dtor = ctorInit->dtor;
     820                                                if ( dtor ) {
     821                                                        ImplicitCtorDtorStmt * implicit = strict_dynamic_cast< ImplicitCtorDtorStmt * >( dtor );
     822                                                        Statement * dtorStmt = implicit->callStmt;
     823
     824                                                        // don't need to call intrinsic dtor, because it does nothing, but
     825                                                        // non-intrinsic dtors must be called
     826                                                        if ( ! isIntrinsicSingleArgCallStmt( dtorStmt ) ) {
     827                                                                // set dtor location to the object's location for error messages
     828                                                                DeclarationWithType * dtorFunc = getDtorFunc( objDecl, dtorStmt, stmtsToAddBefore );
     829                                                                objDecl->attributes.push_back( new Attribute( "cleanup", { new VariableExpr( dtorFunc ) } ) );
     830                                                                ctorInit->dtor = nullptr;
     831                                                        } // if
     832                                                }
    764833                                        } // if
    765834                                } else if ( Initializer * init = ctorInit->init ) {
     
    804873
    805874
    806                 template<typename Iterator, typename OutputIterator>
    807                 void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
    808                         for ( Iterator it = begin ; it != end ; ++it ) {
    809                                 // extract destructor statement from the object decl and insert it into the output. Note that this is
    810                                 // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually
    811                                 // calls an intrinsic dtor then the call must (and will) still be generated since the argument may
    812                                 // contain side effects.
    813                                 ObjectDecl * objDecl = *it;
    814                                 ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() );
    815                                 assert( ctorInit && ctorInit->get_dtor() );
    816                                 *out++ = ctorInit->get_dtor()->clone();
    817                         } // for
    818                 }
    819 
    820                 void InsertDtors::previsit( ObjectDecl * objDecl ) {
    821                         // remember non-static destructed objects so that their destructors can be inserted later
    822                         if ( ! objDecl->get_storageClasses().is_static ) {
    823                                 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
    824                                         // a decision should have been made by the resolver, so ctor and init are not both non-NULL
    825                                         assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
    826                                         Statement * dtor = ctorInit->get_dtor();
    827                                         // don't need to call intrinsic dtor, because it does nothing, but
    828                                         // non-intrinsic dtors must be called
    829                                         if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) {
    830                                                 // set dtor location to the object's location for error messages
    831                                                 ctorInit->dtor->location = objDecl->location;
    832                                                 reverseDeclOrder.front().push_front( objDecl );
    833                                         } // if
    834                                 } // if
    835                         } // if
    836                 }
    837 
    838875                void InsertDtors::previsit( FunctionDecl * funcDecl ) {
    839876                        // each function needs to have its own set of labels
     
    848885                }
    849886
    850                 void InsertDtors::previsit( CompoundStmt * compoundStmt ) {
    851                         // visit statements - this will also populate reverseDeclOrder list.  don't want to dump all destructors
    852                         // when block is left, just the destructors associated with variables defined in this block, so push a new
    853                         // list to the top of the stack so that we can differentiate scopes
    854                         reverseDeclOrder.push_front( OrderedDecls() );
    855                         Parent::previsit( compoundStmt );
    856                 }
    857 
    858                 void InsertDtors::postvisit( CompoundStmt * compoundStmt ) {
    859                         // add destructors for the current scope that we're exiting, unless the last statement is a return, which
    860                         // causes unreachable code warnings
    861                         std::list< Statement * > & statements = compoundStmt->get_kids();
    862                         if ( ! statements.empty() && ! dynamic_cast< ReturnStmt * >( statements.back() ) ) {
    863                                 insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
    864                         }
    865                         reverseDeclOrder.pop_front();
    866                 }
    867 
    868                 void InsertDtors::previsit( ReturnStmt * ) {
    869                         // return exits all scopes, so dump destructors for all scopes
    870                         for ( OrderedDecls & od : reverseDeclOrder ) {
    871                                 insertDtors( od.begin(), od.end(), back_inserter( stmtsToAddBefore ) );
    872                         } // for
    873                 }
    874 
    875887                // Handle break/continue/goto in the same manner as C++.  Basic idea: any objects that are in scope at the
    876888                // BranchStmt but not at the labelled (target) statement must be destructed.  If there are any objects in scope
     
    900912                        if ( ! diff.empty() ) {
    901913                                throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt );
    902                         } // if
    903                         // S_G-S_L results in set of objects that must be destructed
    904                         diff.clear();
    905                         std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) );
    906                         DTOR_PRINT(
    907                                 std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl;
    908                         )
    909                         if ( ! diff.empty() ) {
    910                                 // create an auxilliary set for fast lookup -- can't make diff a set, because diff ordering should be consistent for error messages.
    911                                 std::unordered_set<ObjectDecl *> needsDestructor( diff.begin(), diff.end() );
    912 
    913                                 // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor
    914                                 OrderedDecls ordered;
    915                                 for ( OrderedDecls & rdo : reverseDeclOrder ) {
    916                                         // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order.
    917                                         copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return needsDestructor.count( objDecl ); } );
    918                                 } // for
    919                                 insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAddBefore ) );
    920914                        } // if
    921915                }
     
    943937                }
    944938
     939                void addIds( SymTab::Indexer & indexer, const std::list< DeclarationWithType * > & decls ) {
     940                        for ( auto d : decls ) {
     941                                indexer.addId( d );
     942                        }
     943                }
     944
     945                void addTypes( SymTab::Indexer & indexer, const std::list< TypeDecl * > & tds ) {
     946                        for ( auto td : tds ) {
     947                                indexer.addType( td );
     948                                addIds( indexer, td->assertions );
     949                        }
     950                }
     951
     952                void GenStructMemberCalls::previsit( StructDecl * structDecl ) {
     953                        if ( ! dtorStruct && structDecl->name == "__Destructor" ) {
     954                                dtorStruct = structDecl;
     955                        }
     956                }
     957
    945958                void GenStructMemberCalls::previsit( FunctionDecl * funcDecl ) {
    946959                        GuardValue( function );
     
    955968                        unhandled.clear();
    956969                        usedUninit.clear();
     970
     971                        if ( ! dtorStructDestroy && funcDecl->name == "__destroy_Destructor" ) {
     972                                dtorStructDestroy = funcDecl;
     973                                return;
     974                        }
    957975
    958976                        function = funcDecl;
     
    966984                                if ( structType ) {
    967985                                        structDecl = structType->get_baseStruct();
     986                                        if ( structDecl == dtorStruct ) return;
    968987                                        for ( Declaration * member : structDecl->get_members() ) {
    969988                                                if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
     
    9991018                                // need to explicitly re-add function parameters to the indexer in order to resolve copy constructors
    10001019                                auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this]() { indexer.leaveScope(); } );
    1001                                 indexer.addFunctionType( function->type );
     1020                                addTypes( indexer, function->type->forall );
     1021                                addIds( indexer, function->type->returnVals );
     1022                                addIds( indexer, function->type->parameters );
    10021023
    10031024                                // need to iterate through members in reverse in order for
     
    10141035                                        // insert and resolve default/copy constructor call for each field that's unhandled
    10151036                                        std::list< Statement * > stmt;
    1016                                         Expression * arg2 = nullptr;
     1037                                        Expression * arg2 = 0;
    10171038                                        if ( isCopyConstructor( function ) ) {
    10181039                                                // if copy ctor, need to pass second-param-of-this-function.field
     
    10351056                                                        callStmt->acceptMutator( resolver );
    10361057                                                        if ( isCtor ) {
    1037                                                                 function->get_statements()->push_front( callStmt );
     1058                                                                function->statements->push_front( callStmt );
    10381059                                                        } else {
    10391060                                                                // destructor statements should be added at the end
    1040                                                                 function->get_statements()->push_back( callStmt );
     1061                                                                // function->get_statements()->push_back( callStmt );
     1062
     1063                                                                // Destructor _dtor0 = { &b.a1, (void (*)(void *)_destroy_A };
     1064                                                                std::list< Statement * > stmtsToAdd;
     1065
     1066                                                                static UniqueName memberDtorNamer = { "__memberDtor" };
     1067                                                                assertf( dtorStruct, "builtin __Destructor not found." );
     1068                                                                assertf( dtorStructDestroy, "builtin __destroy_Destructor not found." );
     1069
     1070                                                                Expression * thisExpr = new AddressExpr( new VariableExpr( thisParam ) );
     1071                                                                Expression * dtorExpr = new VariableExpr( getDtorFunc( thisParam, callStmt, stmtsToAdd ) );
     1072
     1073                                                                // cast destructor pointer to void (*)(void *), to silence GCC incompatible pointer warnings
     1074                                                                FunctionType * dtorFtype = new FunctionType( Type::Qualifiers(), false );
     1075                                                                dtorFtype->parameters.push_back( ObjectDecl::newObject( "", new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), nullptr ) );
     1076                                                                Type * dtorType = new PointerType( Type::Qualifiers(), dtorFtype );
     1077
     1078                                                                ObjectDecl * destructor = ObjectDecl::newObject( memberDtorNamer.newName(), new StructInstType( Type::Qualifiers(), dtorStruct ), new ListInit( { new SingleInit( thisExpr ), new SingleInit( new CastExpr( dtorExpr, dtorType ) ) } ) );
     1079                                                                function->statements->push_front( new DeclStmt( noLabels, destructor ) );
     1080                                                                destructor->attributes.push_back( new Attribute( "cleanup", { new VariableExpr( dtorStructDestroy ) } ) );
     1081
     1082                                                                function->statements->kids.splice( function->statements->kids.begin(), stmtsToAdd );
    10411083                                                        }
    10421084                                                } catch ( SemanticError & error ) {
Note: See TracChangeset for help on using the changeset viewer.