Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/SymTab/Autogen.cc

    rbe9288a r108f3cdb  
    1313// Update Count     : 62
    1414//
     15
    1516#include "Autogen.h"
    1617
     
    2425#include <vector>                  // for vector
    2526
    26 #include "AddVisit.h"             // for addVisit
    27 #include "Common/ScopedMap.h"     // for ScopedMap
    28 #include "GenPoly/DeclMutator.h"  // for DeclMutator
    29 #include "GenPoly/ScopedSet.h"    // for ScopedSet
    30 #include "Parser/LinkageSpec.h"   // for AutoGen, Intrinsic, Spec
    31 #include "SymTab/Mangler.h"       // for mangleType
    32 #include "SynTree/Statement.h"    // for SwitchStmt (ptr only), CompoundStmt
    33 #include "SynTree/Type.h"         // for Type, ArrayType, Type::StorageClasses
    34 #include "SynTree/Visitor.h"      // for Visitor
     27#include "AddVisit.h"              // for addVisit
     28#include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
     29#include "Common/ScopedMap.h"      // for ScopedMap<>::const_iterator, Scope...
     30#include "Common/utility.h"        // for cloneAll, operator+
     31#include "GenPoly/DeclMutator.h"   // for DeclMutator
     32#include "GenPoly/ScopedSet.h"     // for ScopedSet, ScopedSet<>::iterator
     33#include "SymTab/Mangler.h"        // for Mangler
     34#include "SynTree/Attribute.h"     // For Attribute
     35#include "SynTree/Mutator.h"       // for maybeMutate
     36#include "SynTree/Statement.h"     // for CompoundStmt, ReturnStmt, ExprStmt
     37#include "SynTree/Type.h"          // for FunctionType, Type, TypeInstType
     38#include "SynTree/Visitor.h"       // for maybeAccept, Visitor, acceptAll
     39
     40class Attribute;
    3541
    3642namespace SymTab {
     
    130136        FunctionType * genDefaultType( Type * paramType ) {
    131137                FunctionType *ftype = new FunctionType( Type::Qualifiers(), false );
    132                 ObjectDecl *dstParam = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new PointerType( Type::Qualifiers(), paramType->clone() ), nullptr );
     138                ObjectDecl *dstParam = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new ReferenceType( Type::Qualifiers(), paramType->clone() ), nullptr );
    133139                ftype->get_parameters().push_back( dstParam );
    134140
     
    152158        }
    153159
    154         /// true if the aggregate's layout is dynamic
    155         template< typename AggrDecl >
    156         bool hasDynamicLayout( AggrDecl * aggregateDecl ) {
    157                 for ( TypeDecl * param : aggregateDecl->get_parameters() ) {
    158                         if ( param->isComplete() ) return true;
    159                 }
    160                 return false;
    161         }
    162 
    163160        /// generate a function decl from a name and type. Nesting depth determines whether
    164161        /// the declaration is static or not; optional paramter determines if declaration is intrinsic
     
    166163                // Routines at global scope marked "static" to prevent multiple definitions in separate translation units
    167164                // because each unit generates copies of the default routines for each aggregate.
    168 //              DeclarationNode::StorageClass sc = functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static;
    169165                Type::StorageClasses scs = functionNesting > 0 ? Type::StorageClasses() : Type::StorageClasses( Type::Static );
    170166                LinkageSpec::Spec spec = isIntrinsic ? LinkageSpec::Intrinsic : LinkageSpec::AutoGen;
     
    181177                        FunctionType * ftype = funcDecl->get_functionType();
    182178                        assert( ! ftype->get_parameters().empty() );
    183                         Type * t = safe_dynamic_cast< PointerType * >( ftype->get_parameters().front()->get_type() )->get_base();
     179                        Type * t = InitTweak::getPointerBase( ftype->get_parameters().front()->get_type() );
     180                        assert( t );
    184181                        map.insert( Mangler::mangleType( t ), true );
    185182                }
     
    188185        /// using map and t, determines if is constructable, etc.
    189186        bool lookup( const TypeMap & map, Type * t ) {
     187                assertf( t, "Autogenerate lookup was given non-type: %s", toString( t ).c_str() );
    190188                if ( dynamic_cast< PointerType * >( t ) ) {
    191189                        // will need more complicated checking if we want this to work with pointer types, since currently
     
    202200
    203201        /// using map and aggr, examines each member to determine if constructor, etc. should be generated
    204         template<typename AggrDecl>
    205         bool shouldGenerate( const TypeMap & map, AggrDecl * aggr ) {
    206                 for ( Declaration * dcl : aggr->get_members() ) {
    207                         if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( dcl ) ) {
    208                                 if ( ! lookup( map, dwt->get_type() ) ) return false;
    209                         }
     202        template<typename Container>
     203        bool shouldGenerate( const TypeMap & map, const Container & container ) {
     204                for ( Type * t : container ) {
     205                        if ( ! lookup( map, t ) ) return false;
    210206                }
    211207                return true;
     
    213209
    214210        /// data structure for abstracting the generation of special functions
    215         template< typename OutputIterator >
     211        template< typename OutputIterator, typename Container >
    216212        struct FuncGenerator {
    217                 StructDecl *aggregateDecl;
    218                 StructInstType *refType;
     213                const Container & container;
     214                Type *refType;
    219215                unsigned int functionNesting;
    220216                const std::list< TypeDecl* > & typeParams;
    221217                OutputIterator out;
    222                 FuncGenerator( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting, const std::list< TypeDecl* > & typeParams, OutputIterator out ) : aggregateDecl( aggregateDecl ), refType( refType ), functionNesting( functionNesting ), typeParams( typeParams ), out( out ) {}
     218                FuncGenerator( const Container & container, Type *refType, unsigned int functionNesting, const std::list< TypeDecl* > & typeParams, OutputIterator out ) : container( container ), refType( refType ), functionNesting( functionNesting ), typeParams( typeParams ), out( out ) {}
    223219
    224220                /// generates a function (?{}, ?=?, ^?{}) based on the data argument and members. If function is generated, inserts the type into the map.
    225221                void gen( const FuncData & data, bool concurrent_type ) {
    226                         if ( ! shouldGenerate( data.map, aggregateDecl ) ) return;
     222                        if ( ! shouldGenerate( data.map, container ) ) return;
    227223                        FunctionType * ftype = data.genType( refType );
    228224
    229                         if(concurrent_type && InitTweak::isDestructor( data.fname )) {
    230                                 ftype->get_parameters().front()->get_type()->set_mutex( true );
    231                         }
    232 
    233                         cloneAll( typeParams, ftype->get_forall() );
     225                        if(concurrent_type && CodeGen::isDestructor( data.fname )) {
     226                                ftype->parameters.front()->get_type()->set_mutex( true );
     227                        }
     228
     229                        cloneAll( typeParams, ftype->forall );
    234230                        *out++ = genFunc( data.fname, ftype, functionNesting );
    235231                        data.map.insert( Mangler::mangleType( refType ), true );
     
    237233        };
    238234
    239         template< typename OutputIterator >
    240         FuncGenerator<OutputIterator> makeFuncGenerator( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting, const std::list< TypeDecl* > & typeParams, OutputIterator out ) {
    241                 return FuncGenerator<OutputIterator>( aggregateDecl, refType, functionNesting, typeParams, out );
     235        template< typename OutputIterator, typename Container >
     236        FuncGenerator<OutputIterator, Container> makeFuncGenerator( const Container & container, Type *refType, unsigned int functionNesting, const std::list< TypeDecl* > & typeParams, OutputIterator out ) {
     237                return FuncGenerator<OutputIterator, Container>( container, refType, functionNesting, typeParams, out );
    242238        }
    243239
     
    279275                FunctionType *copyCtorType = genCopyType( refType->clone() );
    280276
     277                // add unused attribute to parameters of default constructor and destructor
     278                ctorType->get_parameters().front()->get_attributes().push_back( new Attribute( "unused" ) );
     279                dtorType->get_parameters().front()->get_attributes().push_back( new Attribute( "unused" ) );
     280
    281281                // xxx - should we also generate void ?{}(E *, int) and E ?{}(E *, E)?
    282282                // right now these cases work, but that might change.
     
    301301
    302302        /// generates a single struct member operation (constructor call, destructor call, assignment call)
    303         void makeStructMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, bool isDynamicLayout, bool forward = true ) {
    304                 ObjectDecl * returnVal = NULL;
    305                 if ( ! func->get_functionType()->get_returnVals().empty() ) {
    306                         returnVal = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_returnVals().front() );
    307                 }
    308 
     303        void makeStructMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, bool forward = true ) {
    309304                InitTweak::InitExpander srcParam( src );
    310305
    311                 // assign to destination (and return value if generic)
    312                 UntypedExpr *derefExpr = UntypedExpr::createDeref( new VariableExpr( dstParam ) );
    313                 Expression *dstselect = new MemberExpr( field, derefExpr );
     306                // assign to destination
     307                Expression *dstselect = new MemberExpr( field, new CastExpr( new VariableExpr( dstParam ), safe_dynamic_cast< ReferenceType* >( dstParam->get_type() )->get_base()->clone() ) );
    314308                genImplicitCall( srcParam, dstselect, func->get_name(), back_inserter( func->get_statements()->get_kids() ), field, forward );
    315 
    316                 if ( isDynamicLayout && returnVal ) {
    317                         // xxx - there used to be a dereference on returnVal, but this seems to have been wrong?
    318                         Expression *retselect = new MemberExpr( field, new VariableExpr( returnVal ) );
    319                         genImplicitCall( srcParam, retselect, func->get_name(), back_inserter( func->get_statements()->get_kids() ), field, forward );
    320                 } // if
    321309        }
    322310
    323311        /// generates the body of a struct function by iterating the struct members (via parameters) - generates default ctor, copy ctor, assignment, and dtor bodies, but NOT field ctor bodies
    324312        template<typename Iterator>
    325         void makeStructFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool isDynamicLayout, bool forward = true ) {
     313        void makeStructFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward = true ) {
    326314                for ( ; member != end; ++member ) {
    327315                        if ( DeclarationWithType *field = dynamic_cast< DeclarationWithType * >( *member ) ) { // otherwise some form of type declaration, e.g. Aggregate
     
    359347
    360348                                Expression *srcselect = srcParam ? new MemberExpr( field, new VariableExpr( srcParam ) ) : NULL;
    361                                 makeStructMemberOp( dstParam, srcselect, field, func, isDynamicLayout, forward );
     349                                makeStructMemberOp( dstParam, srcselect, field, func, forward );
    362350                        } // if
    363351                } // for
     
    367355        /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
    368356        template<typename Iterator>
    369         void makeStructFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func, bool isDynamicLayout ) {
     357        void makeStructFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func ) {
    370358                FunctionType * ftype = func->get_functionType();
    371359                std::list<DeclarationWithType*> & params = ftype->get_parameters();
     
    393381                                        // matching parameter, initialize field with copy ctor
    394382                                        Expression *srcselect = new VariableExpr(*parameter);
    395                                         makeStructMemberOp( dstParam, srcselect, field, func, isDynamicLayout );
     383                                        makeStructMemberOp( dstParam, srcselect, field, func );
    396384                                        ++parameter;
    397385                                } else {
    398386                                        // no matching parameter, initialize field with default ctor
    399                                         makeStructMemberOp( dstParam, NULL, field, func, isDynamicLayout );
     387                                        makeStructMemberOp( dstParam, NULL, field, func );
    400388                                }
    401389                        }
    402390                }
     391        }
     392
     393        Type * declToType( Declaration * decl ) {
     394                if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( decl ) ) {
     395                        return dwt->get_type();
     396                }
     397                return nullptr;
    403398        }
    404399
     
    413408                // Make function polymorphic in same parameters as generic struct, if applicable
    414409                const std::list< TypeDecl* > & typeParams = aggregateDecl->get_parameters(); // List of type variables to be placed on the generated functions
    415                 bool isDynamicLayout = hasDynamicLayout( aggregateDecl );  // NOTE this flag is an incredibly ugly kludge; we should fix the assignment signature instead (ditto for union)
    416410
    417411                // generate each of the functions based on the supplied FuncData objects
    418412                std::list< FunctionDecl * > newFuncs;
    419                 auto generator = makeFuncGenerator( aggregateDecl, refType, functionNesting, typeParams, back_inserter( newFuncs ) );
     413                // structure that iterates aggregate decl members, returning their types
     414                auto generator = makeFuncGenerator( lazy_map( aggregateDecl->members, declToType ), refType, functionNesting, typeParams, back_inserter( newFuncs ) );
    420415                for ( const FuncData & d : data ) {
    421416                        generator.gen( d, aggregateDecl->is_thread() || aggregateDecl->is_monitor() );
     
    423418
    424419                // field ctors are only generated if default constructor and copy constructor are both generated
    425                 unsigned numCtors = std::count_if( newFuncs.begin(), newFuncs.end(), [](FunctionDecl * dcl) { return InitTweak::isConstructor( dcl->get_name() ); } );
     420                unsigned numCtors = std::count_if( newFuncs.begin(), newFuncs.end(), [](FunctionDecl * dcl) { return CodeGen::isConstructor( dcl->get_name() ); } );
    426421
    427422                if ( functionNesting == 0 ) {
     
    438433                        // generate appropriate calls to member ctor, assignment
    439434                        // destructor needs to do everything in reverse, so pass "forward" based on whether the function is a destructor
    440                         if ( ! InitTweak::isDestructor( dcl->get_name() ) ) {
    441                                 makeStructFunctionBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), dcl, isDynamicLayout );
     435                        if ( ! CodeGen::isDestructor( dcl->get_name() ) ) {
     436                                makeStructFunctionBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), dcl );
    442437                        } else {
    443                                 makeStructFunctionBody( aggregateDecl->get_members().rbegin(), aggregateDecl->get_members().rend(), dcl, isDynamicLayout, false );
    444                         }
    445                         if ( InitTweak::isAssignment( dcl->get_name() ) ) {
     438                                makeStructFunctionBody( aggregateDecl->get_members().rbegin(), aggregateDecl->get_members().rend(), dcl, false );
     439                        }
     440                        if ( CodeGen::isAssignment( dcl->get_name() ) ) {
    446441                                // assignment needs to return a value
    447442                                FunctionType * assignType = dcl->get_functionType();
     
    472467                                        // our inheritance model. I think the correct way to handle this is to
    473468                                        // cast the structure to the type of the member and let the resolver
    474                                         // figure out whether it's valid and have a pass afterwards that fixes
    475                                         // the assignment to use pointer arithmetic with the offset of the
    476                                         // member, much like how generic type members are handled.
     469                                        // figure out whether it's valid/choose the correct unnamed member
    477470                                        continue;
    478471                                }
    479472                                memCtorType->get_parameters().push_back( new ObjectDecl( member->get_name(), Type::StorageClasses(), LinkageSpec::Cforall, 0, member->get_type()->clone(), 0 ) );
    480473                                FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
    481                                 makeStructFieldCtorBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), ctor, isDynamicLayout );
     474                                makeStructFieldCtorBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), ctor );
    482475                                declsToAdd.push_back( ctor );
    483476                        }
     
    490483        void makeUnionFieldsAssignment( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out ) {
    491484                UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
    492                 copy->get_args().push_back( new VariableExpr( dstParam ) );
     485                copy->get_args().push_back( new AddressExpr( new VariableExpr( dstParam ) ) );
    493486                copy->get_args().push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
    494487                copy->get_args().push_back( new SizeofExpr( srcParam->get_type()->clone() ) );
     
    502495                ObjectDecl * dstParam = safe_dynamic_cast< ObjectDecl * >( ftype->get_parameters().front() );
    503496                ObjectDecl * srcParam = safe_dynamic_cast< ObjectDecl * >( ftype->get_parameters().back() );
    504                 ObjectDecl * returnVal = nullptr;
    505                 if ( ! ftype->get_returnVals().empty() ) {
    506                         returnVal = safe_dynamic_cast< ObjectDecl * >( ftype->get_returnVals().front() );
    507                 }
    508497
    509498                makeUnionFieldsAssignment( srcParam, dstParam, back_inserter( funcDecl->get_statements()->get_kids() ) );
    510                 if ( returnVal ) {
     499                if ( CodeGen::isAssignment( funcDecl->get_name() ) ) {
     500                        // also generate return statement in assignment
    511501                        funcDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
    512502                }
     
    535525                cloneAll( typeParams, copyCtorType->get_forall() );
    536526                cloneAll( typeParams, assignType->get_forall() );
     527
     528                // add unused attribute to parameters of default constructor and destructor
     529                ctorType->get_parameters().front()->get_attributes().push_back( new Attribute( "unused" ) );
     530                dtorType->get_parameters().front()->get_attributes().push_back( new Attribute( "unused" ) );
    537531
    538532                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
     
    617611        }
    618612
     613        Type * declToTypeDeclBase( Declaration * decl ) {
     614                if ( TypeDecl * td = dynamic_cast< TypeDecl * >( decl ) ) {
     615                        return td->base;
     616                }
     617                return nullptr;
     618        }
     619
     620        // generate ctor/dtors/assign for typedecls, e.g., otype T = int *;
    619621        void AutogenerateRoutines::visit( TypeDecl *typeDecl ) {
    620                 TypeInstType *typeInst = new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), false );
    621                 typeInst->set_baseType( typeDecl );
    622                 ObjectDecl *src = new ObjectDecl( "_src", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, typeInst->clone(), nullptr );
    623                 ObjectDecl *dst = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new PointerType( Type::Qualifiers(), typeInst->clone() ), nullptr );
    624 
    625                 std::list< Statement * > stmts;
    626                 if ( typeDecl->get_base() ) {
    627                         // xxx - generate ctor/dtors for typedecls, e.g.
    628                         // otype T = int *;
    629                         UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
    630                         assign->get_args().push_back( new CastExpr( new VariableExpr( dst ), new PointerType( Type::Qualifiers(), typeDecl->get_base()->clone() ) ) );
    631                         assign->get_args().push_back( new CastExpr( new VariableExpr( src ), typeDecl->get_base()->clone() ) );
    632                         stmts.push_back( new ReturnStmt( std::list< Label >(), assign ) );
    633                 } // if
    634                 FunctionType *type = new FunctionType( Type::Qualifiers(), false );
    635                 type->get_returnVals().push_back( new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, typeInst, 0 ) );
    636                 type->get_parameters().push_back( dst );
    637                 type->get_parameters().push_back( src );
    638                 FunctionDecl *func = genFunc( "?=?", type, functionNesting );
    639                 func->get_statements()->get_kids() = stmts;
    640                 declsToAddAfter.push_back( func );
     622                if ( ! typeDecl->base ) return;
     623
     624                // generate each of the functions based on the supplied FuncData objects
     625                std::list< FunctionDecl * > newFuncs;
     626                std::list< Declaration * > tds { typeDecl };
     627                std::list< TypeDecl * > typeParams;
     628                TypeInstType refType( Type::Qualifiers(), typeDecl->name, typeDecl );
     629                auto generator = makeFuncGenerator( lazy_map( tds, declToTypeDeclBase ), &refType, functionNesting, typeParams, back_inserter( newFuncs ) );
     630                for ( const FuncData & d : data ) {
     631                        generator.gen( d, false );
     632                }
     633
     634                if ( functionNesting == 0 ) {
     635                        // forward declare if top-level struct, so that
     636                        // type is complete as soon as its body ends
     637                        // Note: this is necessary if we want structs which contain
     638                        // generic (otype) structs as members.
     639                        for ( FunctionDecl * dcl : newFuncs ) {
     640                                addForwardDecl( dcl, declsToAddAfter );
     641                        }
     642                }
     643
     644                for ( FunctionDecl * dcl : newFuncs ) {
     645                        FunctionType * ftype = dcl->type;
     646                        assertf( ftype->parameters.size() == 1 || ftype->parameters.size() == 2, "Incorrect number of parameters in autogenerated typedecl function: %zd", ftype->parameters.size() );
     647                        DeclarationWithType * dst = ftype->parameters.front();
     648                        DeclarationWithType * src = ftype->parameters.size() == 2 ? ftype->parameters.back() : nullptr;
     649                        // generate appropriate calls to member ctor, assignment
     650                        // destructor needs to do everything in reverse, so pass "forward" based on whether the function is a destructor
     651                        UntypedExpr * expr = new UntypedExpr( new NameExpr( dcl->name ) );
     652                        expr->args.push_back( new CastExpr( new VariableExpr( dst ), new ReferenceType( Type::Qualifiers(), typeDecl->base->clone() ) ) );
     653                        if ( src ) expr->args.push_back( new CastExpr( new VariableExpr( src ), typeDecl->base->clone() ) );
     654                        dcl->statements->kids.push_back( new ExprStmt( noLabels, expr ) );
     655                        if ( CodeGen::isAssignment( dcl->get_name() ) ) {
     656                                // assignment needs to return a value
     657                                FunctionType * assignType = dcl->type;
     658                                assert( assignType->parameters.size() == 2 );
     659                                ObjectDecl * srcParam = safe_dynamic_cast< ObjectDecl * >( assignType->parameters.back() );
     660                                dcl->statements->kids.push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
     661                        }
     662                        declsToAddAfter.push_back( dcl );
     663                }
    641664        }
    642665
Note: See TracChangeset for help on using the changeset viewer.