Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/SymTab/Autogen.cc

    r108f3cdb rbe9288a  
    1313// Update Count     : 62
    1414//
    15 
    1615#include "Autogen.h"
    1716
     
    2524#include <vector>                  // for vector
    2625
    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 
    40 class Attribute;
     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
    4135
    4236namespace SymTab {
     
    136130        FunctionType * genDefaultType( Type * paramType ) {
    137131                FunctionType *ftype = new FunctionType( Type::Qualifiers(), false );
    138                 ObjectDecl *dstParam = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new ReferenceType( Type::Qualifiers(), paramType->clone() ), nullptr );
     132                ObjectDecl *dstParam = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new PointerType( Type::Qualifiers(), paramType->clone() ), nullptr );
    139133                ftype->get_parameters().push_back( dstParam );
    140134
     
    158152        }
    159153
     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
    160163        /// generate a function decl from a name and type. Nesting depth determines whether
    161164        /// the declaration is static or not; optional paramter determines if declaration is intrinsic
     
    163166                // Routines at global scope marked "static" to prevent multiple definitions in separate translation units
    164167                // because each unit generates copies of the default routines for each aggregate.
     168//              DeclarationNode::StorageClass sc = functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static;
    165169                Type::StorageClasses scs = functionNesting > 0 ? Type::StorageClasses() : Type::StorageClasses( Type::Static );
    166170                LinkageSpec::Spec spec = isIntrinsic ? LinkageSpec::Intrinsic : LinkageSpec::AutoGen;
     
    177181                        FunctionType * ftype = funcDecl->get_functionType();
    178182                        assert( ! ftype->get_parameters().empty() );
    179                         Type * t = InitTweak::getPointerBase( ftype->get_parameters().front()->get_type() );
    180                         assert( t );
     183                        Type * t = safe_dynamic_cast< PointerType * >( ftype->get_parameters().front()->get_type() )->get_base();
    181184                        map.insert( Mangler::mangleType( t ), true );
    182185                }
     
    185188        /// using map and t, determines if is constructable, etc.
    186189        bool lookup( const TypeMap & map, Type * t ) {
    187                 assertf( t, "Autogenerate lookup was given non-type: %s", toString( t ).c_str() );
    188190                if ( dynamic_cast< PointerType * >( t ) ) {
    189191                        // will need more complicated checking if we want this to work with pointer types, since currently
     
    200202
    201203        /// using map and aggr, examines each member to determine if constructor, etc. should be generated
    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;
     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                        }
    206210                }
    207211                return true;
     
    209213
    210214        /// data structure for abstracting the generation of special functions
    211         template< typename OutputIterator, typename Container >
     215        template< typename OutputIterator >
    212216        struct FuncGenerator {
    213                 const Container & container;
    214                 Type *refType;
     217                StructDecl *aggregateDecl;
     218                StructInstType *refType;
    215219                unsigned int functionNesting;
    216220                const std::list< TypeDecl* > & typeParams;
    217221                OutputIterator 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 ) {}
     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 ) {}
    219223
    220224                /// generates a function (?{}, ?=?, ^?{}) based on the data argument and members. If function is generated, inserts the type into the map.
    221225                void gen( const FuncData & data, bool concurrent_type ) {
    222                         if ( ! shouldGenerate( data.map, container ) ) return;
     226                        if ( ! shouldGenerate( data.map, aggregateDecl ) ) return;
    223227                        FunctionType * ftype = data.genType( refType );
    224228
    225                         if(concurrent_type && CodeGen::isDestructor( data.fname )) {
    226                                 ftype->parameters.front()->get_type()->set_mutex( true );
    227                         }
    228 
    229                         cloneAll( typeParams, ftype->forall );
     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() );
    230234                        *out++ = genFunc( data.fname, ftype, functionNesting );
    231235                        data.map.insert( Mangler::mangleType( refType ), true );
     
    233237        };
    234238
    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 );
     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 );
    238242        }
    239243
     
    275279                FunctionType *copyCtorType = genCopyType( refType->clone() );
    276280
    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 forward = true ) {
     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
    304309                InitTweak::InitExpander srcParam( src );
    305310
    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() ) );
     311                // assign to destination (and return value if generic)
     312                UntypedExpr *derefExpr = UntypedExpr::createDeref( new VariableExpr( dstParam ) );
     313                Expression *dstselect = new MemberExpr( field, derefExpr );
    308314                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
    309321        }
    310322
    311323        /// 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
    312324        template<typename Iterator>
    313         void makeStructFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward = true ) {
     325        void makeStructFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool isDynamicLayout, bool forward = true ) {
    314326                for ( ; member != end; ++member ) {
    315327                        if ( DeclarationWithType *field = dynamic_cast< DeclarationWithType * >( *member ) ) { // otherwise some form of type declaration, e.g. Aggregate
     
    347359
    348360                                Expression *srcselect = srcParam ? new MemberExpr( field, new VariableExpr( srcParam ) ) : NULL;
    349                                 makeStructMemberOp( dstParam, srcselect, field, func, forward );
     361                                makeStructMemberOp( dstParam, srcselect, field, func, isDynamicLayout, forward );
    350362                        } // if
    351363                } // for
     
    355367        /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
    356368        template<typename Iterator>
    357         void makeStructFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func ) {
     369        void makeStructFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func, bool isDynamicLayout ) {
    358370                FunctionType * ftype = func->get_functionType();
    359371                std::list<DeclarationWithType*> & params = ftype->get_parameters();
     
    381393                                        // matching parameter, initialize field with copy ctor
    382394                                        Expression *srcselect = new VariableExpr(*parameter);
    383                                         makeStructMemberOp( dstParam, srcselect, field, func );
     395                                        makeStructMemberOp( dstParam, srcselect, field, func, isDynamicLayout );
    384396                                        ++parameter;
    385397                                } else {
    386398                                        // no matching parameter, initialize field with default ctor
    387                                         makeStructMemberOp( dstParam, NULL, field, func );
     399                                        makeStructMemberOp( dstParam, NULL, field, func, isDynamicLayout );
    388400                                }
    389401                        }
    390402                }
    391         }
    392 
    393         Type * declToType( Declaration * decl ) {
    394                 if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( decl ) ) {
    395                         return dwt->get_type();
    396                 }
    397                 return nullptr;
    398403        }
    399404
     
    408413                // Make function polymorphic in same parameters as generic struct, if applicable
    409414                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)
    410416
    411417                // generate each of the functions based on the supplied FuncData objects
    412418                std::list< FunctionDecl * > 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 ) );
     419                auto generator = makeFuncGenerator( aggregateDecl, refType, functionNesting, typeParams, back_inserter( newFuncs ) );
    415420                for ( const FuncData & d : data ) {
    416421                        generator.gen( d, aggregateDecl->is_thread() || aggregateDecl->is_monitor() );
     
    418423
    419424                // field ctors are only generated if default constructor and copy constructor are both generated
    420                 unsigned numCtors = std::count_if( newFuncs.begin(), newFuncs.end(), [](FunctionDecl * dcl) { return CodeGen::isConstructor( dcl->get_name() ); } );
     425                unsigned numCtors = std::count_if( newFuncs.begin(), newFuncs.end(), [](FunctionDecl * dcl) { return InitTweak::isConstructor( dcl->get_name() ); } );
    421426
    422427                if ( functionNesting == 0 ) {
     
    433438                        // generate appropriate calls to member ctor, assignment
    434439                        // destructor needs to do everything in reverse, so pass "forward" based on whether the function is a destructor
    435                         if ( ! CodeGen::isDestructor( dcl->get_name() ) ) {
    436                                 makeStructFunctionBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), dcl );
     440                        if ( ! InitTweak::isDestructor( dcl->get_name() ) ) {
     441                                makeStructFunctionBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), dcl, isDynamicLayout );
    437442                        } else {
    438                                 makeStructFunctionBody( aggregateDecl->get_members().rbegin(), aggregateDecl->get_members().rend(), dcl, false );
    439                         }
    440                         if ( CodeGen::isAssignment( dcl->get_name() ) ) {
     443                                makeStructFunctionBody( aggregateDecl->get_members().rbegin(), aggregateDecl->get_members().rend(), dcl, isDynamicLayout, false );
     444                        }
     445                        if ( InitTweak::isAssignment( dcl->get_name() ) ) {
    441446                                // assignment needs to return a value
    442447                                FunctionType * assignType = dcl->get_functionType();
     
    467472                                        // our inheritance model. I think the correct way to handle this is to
    468473                                        // cast the structure to the type of the member and let the resolver
    469                                         // figure out whether it's valid/choose the correct unnamed member
     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.
    470477                                        continue;
    471478                                }
    472479                                memCtorType->get_parameters().push_back( new ObjectDecl( member->get_name(), Type::StorageClasses(), LinkageSpec::Cforall, 0, member->get_type()->clone(), 0 ) );
    473480                                FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
    474                                 makeStructFieldCtorBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), ctor );
     481                                makeStructFieldCtorBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), ctor, isDynamicLayout );
    475482                                declsToAdd.push_back( ctor );
    476483                        }
     
    483490        void makeUnionFieldsAssignment( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out ) {
    484491                UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
    485                 copy->get_args().push_back( new AddressExpr( new VariableExpr( dstParam ) ) );
     492                copy->get_args().push_back( new VariableExpr( dstParam ) );
    486493                copy->get_args().push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
    487494                copy->get_args().push_back( new SizeofExpr( srcParam->get_type()->clone() ) );
     
    495502                ObjectDecl * dstParam = safe_dynamic_cast< ObjectDecl * >( ftype->get_parameters().front() );
    496503                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                }
    497508
    498509                makeUnionFieldsAssignment( srcParam, dstParam, back_inserter( funcDecl->get_statements()->get_kids() ) );
    499                 if ( CodeGen::isAssignment( funcDecl->get_name() ) ) {
    500                         // also generate return statement in assignment
     510                if ( returnVal ) {
    501511                        funcDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
    502512                }
     
    525535                cloneAll( typeParams, copyCtorType->get_forall() );
    526536                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" ) );
    531537
    532538                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
     
    611617        }
    612618
    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 *;
    621619        void AutogenerateRoutines::visit( TypeDecl *typeDecl ) {
    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                 }
     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 );
    664641        }
    665642
Note: See TracChangeset for help on using the changeset viewer.