source: src/SymTab/Autogen.cc @ d48e529

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since d48e529 was 4e8949f, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Handle ConstructorExpr? in CodeGenerator?

  • Property mode set to 100644
File size: 38.1 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Autogen.cc --
8//
9// Author           : Rob Schluntz
10// Created On       : Thu Mar 03 15:45:56 2016
11// Last Modified By : Andrew Beach
12// Last Modified On : Fri Jul 14 16:41:00 2017
13// Update Count     : 62
14//
15
16#include "Autogen.h"
17
18#include <cstddef>                 // for NULL
19#include <algorithm>               // for count_if
20#include <cassert>                 // for strict_dynamic_cast, assert, assertf
21#include <iterator>                // for back_insert_iterator, back_inserter
22#include <list>                    // for list, _List_iterator, list<>::iter...
23#include <set>                     // for set, _Rb_tree_const_iterator
24#include <utility>                 // for pair
25#include <vector>                  // for vector
26
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;
41
42namespace SymTab {
43        Type * SizeType = 0;
44        typedef ScopedMap< std::string, bool > TypeMap;
45
46        /// Data used to generate functions generically. Specifically, the name of the generated function, a function which generates the routine protoype, and a map which contains data to determine whether a function should be generated.
47        struct FuncData {
48                typedef FunctionType * (*TypeGen)( Type * );
49                FuncData( const std::string & fname, const TypeGen & genType, TypeMap & map ) : fname( fname ), genType( genType ), map( map ) {}
50                std::string fname;
51                TypeGen genType;
52                TypeMap & map;
53        };
54
55        class AutogenerateRoutines final : public Visitor {
56            template< typename Visitor >
57            friend void acceptAndAdd( std::list< Declaration * > &translationUnit, Visitor &visitor );
58            template< typename Visitor >
59            friend void addVisitStatementList( std::list< Statement* > &stmts, Visitor &visitor );
60          public:
61                std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
62
63                typedef Visitor Parent;
64                using Parent::visit;
65
66                AutogenerateRoutines();
67
68                virtual void visit( EnumDecl *enumDecl );
69                virtual void visit( StructDecl *structDecl );
70                virtual void visit( UnionDecl *structDecl );
71                virtual void visit( TypeDecl *typeDecl );
72                virtual void visit( TraitDecl *ctxDecl );
73                virtual void visit( FunctionDecl *functionDecl );
74
75                virtual void visit( FunctionType *ftype );
76                virtual void visit( PointerType *ftype );
77
78                virtual void visit( CompoundStmt *compoundStmt );
79                virtual void visit( SwitchStmt *switchStmt );
80
81          private:
82                template< typename StmtClass > void visitStatement( StmtClass *stmt );
83
84                std::list< Declaration * > declsToAdd, declsToAddAfter;
85                std::set< std::string > structsDone;
86                unsigned int functionNesting = 0;     // current level of nested functions
87                /// Note: the following maps could be ScopedSets, but it should be easier to work
88                /// deleted functions in if they are maps, since the value false can be inserted
89                /// at the current scope without affecting outer scopes or requiring copies.
90                TypeMap copyable, assignable, constructable, destructable;
91                std::vector< FuncData > data;
92        };
93
94        /// generates routines for tuple types.
95        /// Doesn't really need to be a mutator, but it's easier to reuse DeclMutator than it is to use AddVisit
96        /// or anything we currently have that supports adding new declarations for visitors
97        class AutogenTupleRoutines : public GenPoly::DeclMutator {
98          public:
99                typedef GenPoly::DeclMutator Parent;
100                using Parent::mutate;
101
102                virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
103
104                virtual Type * mutate( TupleType *tupleType );
105
106                virtual CompoundStmt * mutate( CompoundStmt *compoundStmt );
107
108          private:
109                unsigned int functionNesting = 0;     // current level of nested functions
110                GenPoly::ScopedSet< std::string > seenTuples;
111        };
112
113        void autogenerateRoutines( std::list< Declaration * > &translationUnit ) {
114                AutogenerateRoutines generator;
115                acceptAndAdd( translationUnit, generator );
116
117                // needs to be done separately because AutogenerateRoutines skips types that appear as function arguments, etc.
118                // AutogenTupleRoutines tupleGenerator;
119                // tupleGenerator.mutateDeclarationList( translationUnit );
120        }
121
122        bool isUnnamedBitfield( ObjectDecl * obj ) {
123                return obj != NULL && obj->get_name() == "" && obj->get_bitfieldWidth() != NULL;
124        }
125
126        /// inserts a forward declaration for functionDecl into declsToAdd
127        void addForwardDecl( FunctionDecl * functionDecl, std::list< Declaration * > & declsToAdd ) {
128                FunctionDecl * decl = functionDecl->clone();
129                delete decl->get_statements();
130                decl->set_statements( NULL );
131                declsToAdd.push_back( decl );
132                decl->fixUniqueId();
133        }
134
135        /// given type T, generate type of default ctor/dtor, i.e. function type void (*) (T *)
136        FunctionType * genDefaultType( Type * paramType ) {
137                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 );
139                ftype->get_parameters().push_back( dstParam );
140
141                return ftype;
142        }
143
144        /// given type T, generate type of copy ctor, i.e. function type void (*) (T *, T)
145        FunctionType * genCopyType( Type * paramType ) {
146                FunctionType *ftype = genDefaultType( paramType );
147                ObjectDecl *srcParam = new ObjectDecl( "_src", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
148                ftype->get_parameters().push_back( srcParam );
149                return ftype;
150        }
151
152        /// given type T, generate type of assignment, i.e. function type T (*) (T *, T)
153        FunctionType * genAssignType( Type * paramType ) {
154                FunctionType *ftype = genCopyType( paramType );
155                ObjectDecl *returnVal = new ObjectDecl( "_ret", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
156                ftype->get_returnVals().push_back( returnVal );
157                return ftype;
158        }
159
160        /// generate a function decl from a name and type. Nesting depth determines whether
161        /// the declaration is static or not; optional paramter determines if declaration is intrinsic
162        FunctionDecl * genFunc( const std::string & fname, FunctionType * ftype, unsigned int functionNesting, bool isIntrinsic = false  ) {
163                // Routines at global scope marked "static" to prevent multiple definitions in separate translation units
164                // because each unit generates copies of the default routines for each aggregate.
165                Type::StorageClasses scs = functionNesting > 0 ? Type::StorageClasses() : Type::StorageClasses( Type::Static );
166                LinkageSpec::Spec spec = isIntrinsic ? LinkageSpec::Intrinsic : LinkageSpec::AutoGen;
167                FunctionDecl * decl = new FunctionDecl( fname, scs, spec, ftype, new CompoundStmt( noLabels ),
168                                                                                                std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) );
169                decl->fixUniqueId();
170                return decl;
171        }
172
173        /// inserts base type of first argument into map if pred(funcDecl) is true
174        void insert( FunctionDecl *funcDecl, TypeMap & map, FunctionDecl * (*pred)(Declaration *) ) {
175                // insert type into constructable, etc. map if appropriate
176                if ( pred( funcDecl ) ) {
177                        FunctionType * ftype = funcDecl->get_functionType();
178                        assert( ! ftype->get_parameters().empty() );
179                        Type * t = InitTweak::getPointerBase( ftype->get_parameters().front()->get_type() );
180                        assert( t );
181                        map.insert( Mangler::mangleType( t ), true );
182                }
183        }
184
185        /// using map and t, determines if is constructable, etc.
186        bool lookup( const TypeMap & map, Type * t ) {
187                assertf( t, "Autogenerate lookup was given non-type: %s", toString( t ).c_str() );
188                if ( dynamic_cast< PointerType * >( t ) ) {
189                        // will need more complicated checking if we want this to work with pointer types, since currently
190                        return true;
191                } else if ( ArrayType * at = dynamic_cast< ArrayType * >( t ) ) {
192                        // an array's constructor, etc. is generated on the fly based on the base type's constructor, etc.
193                        return lookup( map, at->get_base() );
194                }
195                TypeMap::const_iterator it = map.find( Mangler::mangleType( t ) );
196                if ( it != map.end() ) return it->second;
197                // something that does not appear in the map is by default not constructable, etc.
198                return false;
199        }
200
201        /// 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;
206                }
207                return true;
208        }
209
210        /// data structure for abstracting the generation of special functions
211        template< typename OutputIterator, typename Container >
212        struct FuncGenerator {
213                const Container & container;
214                Type *refType;
215                unsigned int functionNesting;
216                const std::list< TypeDecl* > & typeParams;
217                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 ) {}
219
220                /// generates a function (?{}, ?=?, ^?{}) based on the data argument and members. If function is generated, inserts the type into the map.
221                void gen( const FuncData & data, bool concurrent_type ) {
222                        if ( ! shouldGenerate( data.map, container ) ) return;
223                        FunctionType * ftype = data.genType( refType );
224
225                        if ( concurrent_type && CodeGen::isDestructor( data.fname ) ) {
226                                ftype->parameters.front()->get_type()->set_mutex( true );
227                        }
228
229                        cloneAll( typeParams, ftype->forall );
230                        *out++ = genFunc( data.fname, ftype, functionNesting );
231                        data.map.insert( Mangler::mangleType( refType ), true );
232                }
233        };
234
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 );
238        }
239
240        /// generates a single enumeration assignment expression
241        ApplicationExpr * genEnumAssign( FunctionType * ftype, FunctionDecl * assignDecl ) {
242                // enum copy construct and assignment is just C-style assignment.
243                // this looks like a bad recursive call, but code gen will turn it into
244                // a C-style assignment.
245                // This happens before function pointer type conversion, so need to do it manually here
246                // NOTE: ftype is not necessarily the functionType belonging to assignDecl - ftype is the
247                // type of the function that this expression is being generated for (so that the correct
248                // parameters) are using in the variable exprs
249                assert( ftype->get_parameters().size() == 2 );
250                ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->get_parameters().front() );
251                ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( ftype->get_parameters().back() );
252
253                VariableExpr * assignVarExpr = new VariableExpr( assignDecl );
254                Type * assignVarExprType = assignVarExpr->get_result();
255                assignVarExprType = new PointerType( Type::Qualifiers(), assignVarExprType );
256                assignVarExpr->set_result( assignVarExprType );
257                ApplicationExpr * assignExpr = new ApplicationExpr( assignVarExpr );
258                assignExpr->get_args().push_back( new VariableExpr( dstParam ) );
259                assignExpr->get_args().push_back( new VariableExpr( srcParam ) );
260                return assignExpr;
261        }
262
263        // E ?=?(E volatile*, int),
264        //   ?=?(E _Atomic volatile*, int);
265        void makeEnumFunctions( EnumInstType *refType, unsigned int functionNesting, std::list< Declaration * > &declsToAdd ) {
266
267                // T ?=?(E *, E);
268                FunctionType *assignType = genAssignType( refType );
269
270                // void ?{}(E *); void ^?{}(E *);
271                FunctionType * ctorType = genDefaultType( refType->clone() );
272                FunctionType * dtorType = genDefaultType( refType->clone() );
273
274                // void ?{}(E *, E);
275                FunctionType *copyCtorType = genCopyType( refType->clone() );
276
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
281                // xxx - should we also generate void ?{}(E *, int) and E ?{}(E *, E)?
282                // right now these cases work, but that might change.
283
284                // xxx - Temporary: make these functions intrinsic so they codegen as C assignment.
285                // Really they're something of a cross between instrinsic and autogen, so should
286                // probably make a new linkage type
287                FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting, true );
288                FunctionDecl *ctorDecl = genFunc( "?{}", ctorType, functionNesting, true );
289                FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting, true );
290                FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting, true );
291
292                // body is either return stmt or expr stmt
293                assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, genEnumAssign( assignType, assignDecl ) ) );
294                copyCtorDecl->get_statements()->get_kids().push_back( new ExprStmt( noLabels, genEnumAssign( copyCtorType, assignDecl ) ) );
295
296                declsToAdd.push_back( ctorDecl );
297                declsToAdd.push_back( copyCtorDecl );
298                declsToAdd.push_back( dtorDecl );
299                declsToAdd.push_back( assignDecl ); // assignment should come last since it uses copy constructor in return
300        }
301
302        /// 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 ) {
304                InitTweak::InitExpander srcParam( src );
305
306                // assign to destination
307                Expression *dstselect = new MemberExpr( field, new CastExpr( new VariableExpr( dstParam ), strict_dynamic_cast< ReferenceType* >( dstParam->get_type() )->get_base()->clone() ) );
308                genImplicitCall( srcParam, dstselect, func->get_name(), back_inserter( func->get_statements()->get_kids() ), field, forward );
309        }
310
311        /// 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
312        template<typename Iterator>
313        void makeStructFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward = true ) {
314                for ( ; member != end; ++member ) {
315                        if ( DeclarationWithType *field = dynamic_cast< DeclarationWithType * >( *member ) ) { // otherwise some form of type declaration, e.g. Aggregate
316                                // query the type qualifiers of this field and skip assigning it if it is marked const.
317                                // If it is an array type, we need to strip off the array layers to find its qualifiers.
318                                Type * type = field->get_type();
319                                while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
320                                        type = at->get_base();
321                                }
322
323                                if ( type->get_const() && func->get_name() == "?=?" ) {
324                                        // don't assign const members, but do construct/destruct
325                                        continue;
326                                }
327
328                                if ( field->get_name() == "" ) {
329                                        // don't assign to anonymous members
330                                        // xxx - this is a temporary fix. Anonymous members tie into
331                                        // our inheritance model. I think the correct way to handle this is to
332                                        // cast the structure to the type of the member and let the resolver
333                                        // figure out whether it's valid and have a pass afterwards that fixes
334                                        // the assignment to use pointer arithmetic with the offset of the
335                                        // member, much like how generic type members are handled.
336                                        continue;
337                                }
338
339                                assert( ! func->get_functionType()->get_parameters().empty() );
340                                ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().front() );
341                                ObjectDecl * srcParam = NULL;
342                                if ( func->get_functionType()->get_parameters().size() == 2 ) {
343                                        srcParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().back() );
344                                }
345                                // srcParam may be NULL, in which case we have default ctor/dtor
346                                assert( dstParam );
347
348                                Expression *srcselect = srcParam ? new MemberExpr( field, new VariableExpr( srcParam ) ) : NULL;
349                                makeStructMemberOp( dstParam, srcselect, field, func, forward );
350                        } // if
351                } // for
352        } // makeStructFunctionBody
353
354        /// generate the body of a constructor which takes parameters that match fields, e.g.
355        /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
356        template<typename Iterator>
357        void makeStructFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func ) {
358                FunctionType * ftype = func->get_functionType();
359                std::list<DeclarationWithType*> & params = ftype->get_parameters();
360                assert( params.size() >= 2 );  // should not call this function for default ctor, etc.
361
362                // skip 'this' parameter
363                ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( params.front() );
364                assert( dstParam );
365                std::list<DeclarationWithType*>::iterator parameter = params.begin()+1;
366                for ( ; member != end; ++member ) {
367                        if ( DeclarationWithType * field = dynamic_cast<DeclarationWithType*>( *member ) ) {
368                                if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
369                                        // don't make a function whose parameter is an unnamed bitfield
370                                        continue;
371                                } else if ( field->get_name() == "" ) {
372                                        // don't assign to anonymous members
373                                        // xxx - this is a temporary fix. Anonymous members tie into
374                                        // our inheritance model. I think the correct way to handle this is to
375                                        // cast the structure to the type of the member and let the resolver
376                                        // figure out whether it's valid and have a pass afterwards that fixes
377                                        // the assignment to use pointer arithmetic with the offset of the
378                                        // member, much like how generic type members are handled.
379                                        continue;
380                                } else if ( parameter != params.end() ) {
381                                        // matching parameter, initialize field with copy ctor
382                                        Expression *srcselect = new VariableExpr(*parameter);
383                                        makeStructMemberOp( dstParam, srcselect, field, func );
384                                        ++parameter;
385                                } else {
386                                        // no matching parameter, initialize field with default ctor
387                                        makeStructMemberOp( dstParam, NULL, field, func );
388                                }
389                        }
390                }
391        }
392
393        Type * declToType( Declaration * decl ) {
394                if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( decl ) ) {
395                        return dwt->get_type();
396                }
397                return nullptr;
398        }
399
400        /// generates struct constructors, destructor, and assignment functions
401        void makeStructFunctions( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting, std::list< Declaration * > & declsToAdd, const std::vector< FuncData > & data ) {
402                // Builtins do not use autogeneration.
403                if ( aggregateDecl->get_linkage() == LinkageSpec::BuiltinCFA ||
404                         aggregateDecl->get_linkage() == LinkageSpec::BuiltinC ) {
405                        return;
406                }
407
408                // Make function polymorphic in same parameters as generic struct, if applicable
409                const std::list< TypeDecl* > & typeParams = aggregateDecl->get_parameters(); // List of type variables to be placed on the generated functions
410
411                // generate each of the functions based on the supplied FuncData objects
412                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 ) );
415                for ( const FuncData & d : data ) {
416                        generator.gen( d, aggregateDecl->is_thread() || aggregateDecl->is_monitor() );
417                }
418
419                // 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() ); } );
421
422                if ( functionNesting == 0 ) {
423                        // forward declare if top-level struct, so that
424                        // type is complete as soon as its body ends
425                        // Note: this is necessary if we want structs which contain
426                        // generic (otype) structs as members.
427                        for ( FunctionDecl * dcl : newFuncs ) {
428                                addForwardDecl( dcl, declsToAdd );
429                        }
430                }
431
432                for ( FunctionDecl * dcl : newFuncs ) {
433                        // generate appropriate calls to member ctor, assignment
434                        // 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 );
437                        } else {
438                                makeStructFunctionBody( aggregateDecl->get_members().rbegin(), aggregateDecl->get_members().rend(), dcl, false );
439                        }
440                        if ( CodeGen::isAssignment( dcl->get_name() ) ) {
441                                // assignment needs to return a value
442                                FunctionType * assignType = dcl->get_functionType();
443                                assert( assignType->get_parameters().size() == 2 );
444                                ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( assignType->get_parameters().back() );
445                                dcl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
446                        }
447                        declsToAdd.push_back( dcl );
448                }
449
450                // create constructors which take each member type as a parameter.
451                // for example, for struct A { int x, y; }; generate
452                //   void ?{}(A *, int) and void ?{}(A *, int, int)
453                // Field constructors are only generated if default and copy constructor
454                // are generated, since they need access to both
455                if ( numCtors == 2 ) {
456                        FunctionType * memCtorType = genDefaultType( refType );
457                        cloneAll( typeParams, memCtorType->get_forall() );
458                        for ( std::list<Declaration *>::iterator i = aggregateDecl->get_members().begin(); i != aggregateDecl->get_members().end(); ++i ) {
459                                DeclarationWithType * member = dynamic_cast<DeclarationWithType *>( *i );
460                                assert( member );
461                                if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( member ) ) ) {
462                                        // don't make a function whose parameter is an unnamed bitfield
463                                        continue;
464                                } else if ( member->get_name() == "" ) {
465                                        // don't assign to anonymous members
466                                        // xxx - this is a temporary fix. Anonymous members tie into
467                                        // our inheritance model. I think the correct way to handle this is to
468                                        // 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
470                                        continue;
471                                }
472                                memCtorType->get_parameters().push_back( new ObjectDecl( member->get_name(), Type::StorageClasses(), LinkageSpec::Cforall, 0, member->get_type()->clone(), 0 ) );
473                                FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
474                                makeStructFieldCtorBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), ctor );
475                                declsToAdd.push_back( ctor );
476                        }
477                        delete memCtorType;
478                }
479        }
480
481        /// generate a single union assignment expression (using memcpy)
482        template< typename OutputIterator >
483        void makeUnionFieldsAssignment( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out ) {
484                UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
485                copy->get_args().push_back( new AddressExpr( new VariableExpr( dstParam ) ) );
486                copy->get_args().push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
487                copy->get_args().push_back( new SizeofExpr( srcParam->get_type()->clone() ) );
488                *out++ = new ExprStmt( noLabels, copy );
489        }
490
491        /// generates the body of a union assignment/copy constructor/field constructor
492        void makeUnionAssignBody( FunctionDecl * funcDecl ) {
493                FunctionType * ftype = funcDecl->get_functionType();
494                assert( ftype->get_parameters().size() == 2 );
495                ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->get_parameters().front() );
496                ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( ftype->get_parameters().back() );
497
498                makeUnionFieldsAssignment( srcParam, dstParam, back_inserter( funcDecl->get_statements()->get_kids() ) );
499                if ( CodeGen::isAssignment( funcDecl->get_name() ) ) {
500                        // also generate return statement in assignment
501                        funcDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
502                }
503        }
504
505        /// generates union constructors, destructors, and assignment operator
506        void makeUnionFunctions( UnionDecl *aggregateDecl, UnionInstType *refType, unsigned int functionNesting, std::list< Declaration * > & declsToAdd ) {
507                // Make function polymorphic in same parameters as generic union, if applicable
508                const std::list< TypeDecl* > & typeParams = aggregateDecl->get_parameters(); // List of type variables to be placed on the generated functions
509
510                // default ctor/dtor need only first parameter
511                // void ?{}(T *); void ^?{}(T *);
512                FunctionType *ctorType = genDefaultType( refType );
513                FunctionType *dtorType = genDefaultType( refType );
514
515                // copy ctor needs both parameters
516                // void ?{}(T *, T);
517                FunctionType *copyCtorType = genCopyType( refType );
518
519                // assignment needs both and return value
520                // T ?=?(T *, T);
521                FunctionType *assignType = genAssignType( refType );
522
523                cloneAll( typeParams, ctorType->get_forall() );
524                cloneAll( typeParams, dtorType->get_forall() );
525                cloneAll( typeParams, copyCtorType->get_forall() );
526                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" ) );
531
532                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
533                // because each unit generates copies of the default routines for each aggregate.
534                FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting );
535                FunctionDecl *ctorDecl = genFunc( "?{}",  ctorType, functionNesting );
536                FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting );
537                FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting );
538
539                makeUnionAssignBody( assignDecl );
540
541                // body of assignment and copy ctor is the same
542                makeUnionAssignBody( copyCtorDecl );
543
544                // create a constructor which takes the first member type as a parameter.
545                // for example, for Union A { int x; double y; }; generate
546                // void ?{}(A *, int)
547                // This is to mimic C's behaviour which initializes the first member of the union.
548                std::list<Declaration *> memCtors;
549                for ( Declaration * member : aggregateDecl->get_members() ) {
550                        if ( DeclarationWithType * field = dynamic_cast< DeclarationWithType * >( member ) ) {
551                                ObjectDecl * srcParam = new ObjectDecl( "src", Type::StorageClasses(), LinkageSpec::Cforall, 0, field->get_type()->clone(), 0 );
552
553                                FunctionType * memCtorType = ctorType->clone();
554                                memCtorType->get_parameters().push_back( srcParam );
555                                FunctionDecl * ctor = genFunc( "?{}", memCtorType, functionNesting );
556
557                                makeUnionAssignBody( ctor );
558                                memCtors.push_back( ctor );
559                                // only generate a ctor for the first field
560                                break;
561                        }
562                }
563
564                declsToAdd.push_back( ctorDecl );
565                declsToAdd.push_back( copyCtorDecl );
566                declsToAdd.push_back( dtorDecl );
567                declsToAdd.push_back( assignDecl ); // assignment should come last since it uses copy constructor in return
568                declsToAdd.splice( declsToAdd.end(), memCtors );
569        }
570
571        AutogenerateRoutines::AutogenerateRoutines() {
572                // the order here determines the order that these functions are generated.
573                // assignment should come last since it uses copy constructor in return.
574                data.push_back( FuncData( "?{}", genDefaultType, constructable ) );
575                data.push_back( FuncData( "?{}", genCopyType, copyable ) );
576                data.push_back( FuncData( "^?{}", genDefaultType, destructable ) );
577                data.push_back( FuncData( "?=?", genAssignType, assignable ) );
578        }
579
580        void AutogenerateRoutines::visit( EnumDecl *enumDecl ) {
581                if ( ! enumDecl->get_members().empty() ) {
582                        EnumInstType *enumInst = new EnumInstType( Type::Qualifiers(), enumDecl->get_name() );
583                        // enumInst->set_baseEnum( enumDecl );
584                        makeEnumFunctions( enumInst, functionNesting, declsToAddAfter );
585                }
586        }
587
588        void AutogenerateRoutines::visit( StructDecl *structDecl ) {
589                if ( structDecl->has_body() && structsDone.find( structDecl->get_name() ) == structsDone.end() ) {
590                        StructInstType structInst( Type::Qualifiers(), structDecl->get_name() );
591                        for ( TypeDecl * typeDecl : structDecl->get_parameters() ) {
592                                // need to visit assertions so that they are added to the appropriate maps
593                                acceptAll( typeDecl->get_assertions(), *this );
594                                structInst.get_parameters().push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), typeDecl ) ) );
595                        }
596                        structInst.set_baseStruct( structDecl );
597                        makeStructFunctions( structDecl, &structInst, functionNesting, declsToAddAfter, data );
598                        structsDone.insert( structDecl->get_name() );
599                } // if
600        }
601
602        void AutogenerateRoutines::visit( UnionDecl *unionDecl ) {
603                if ( ! unionDecl->get_members().empty() ) {
604                        UnionInstType unionInst( Type::Qualifiers(), unionDecl->get_name() );
605                        unionInst.set_baseUnion( unionDecl );
606                        for ( TypeDecl * typeDecl : unionDecl->get_parameters() ) {
607                                unionInst.get_parameters().push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), typeDecl ) ) );
608                        }
609                        makeUnionFunctions( unionDecl, &unionInst, functionNesting, declsToAddAfter );
610                } // if
611        }
612
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 *;
621        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 = strict_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                }
664        }
665
666        void addDecls( std::list< Declaration * > &declsToAdd, std::list< Statement * > &statements, std::list< Statement * >::iterator i ) {
667                for ( std::list< Declaration * >::iterator decl = declsToAdd.begin(); decl != declsToAdd.end(); ++decl ) {
668                        statements.insert( i, new DeclStmt( noLabels, *decl ) );
669                } // for
670                declsToAdd.clear();
671        }
672
673        void AutogenerateRoutines::visit( FunctionType *) {
674                // ensure that we don't add assignment ops for types defined as part of the function
675        }
676
677        void AutogenerateRoutines::visit( PointerType *) {
678                // ensure that we don't add assignment ops for types defined as part of the pointer
679        }
680
681        void AutogenerateRoutines::visit( TraitDecl *) {
682                // ensure that we don't add assignment ops for types defined as part of the trait
683        }
684
685        template< typename StmtClass >
686        inline void AutogenerateRoutines::visitStatement( StmtClass *stmt ) {
687                std::set< std::string > oldStructs = structsDone;
688                addVisit( stmt, *this );
689                structsDone = oldStructs;
690        }
691
692        void AutogenerateRoutines::visit( FunctionDecl *functionDecl ) {
693                // record the existence of this function as appropriate
694                insert( functionDecl, constructable, InitTweak::isDefaultConstructor );
695                insert( functionDecl, assignable, InitTweak::isAssignment );
696                insert( functionDecl, copyable, InitTweak::isCopyConstructor );
697                insert( functionDecl, destructable, InitTweak::isDestructor );
698
699                maybeAccept( functionDecl->get_functionType(), *this );
700                functionNesting += 1;
701                maybeAccept( functionDecl->get_statements(), *this );
702                functionNesting -= 1;
703        }
704
705        void AutogenerateRoutines::visit( CompoundStmt *compoundStmt ) {
706                constructable.beginScope();
707                assignable.beginScope();
708                copyable.beginScope();
709                destructable.beginScope();
710                visitStatement( compoundStmt );
711                constructable.endScope();
712                assignable.endScope();
713                copyable.endScope();
714                destructable.endScope();
715        }
716
717        void AutogenerateRoutines::visit( SwitchStmt *switchStmt ) {
718                visitStatement( switchStmt );
719        }
720
721        void makeTupleFunctionBody( FunctionDecl * function ) {
722                FunctionType * ftype = function->get_functionType();
723                assertf( ftype->get_parameters().size() == 1 || ftype->get_parameters().size() == 2, "too many parameters in generated tuple function" );
724
725                UntypedExpr * untyped = new UntypedExpr( new NameExpr( function->get_name() ) );
726
727                /// xxx - &* is used to make this easier for later passes to handle
728                untyped->get_args().push_back( new AddressExpr( UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
729                if ( ftype->get_parameters().size() == 2 ) {
730                        untyped->get_args().push_back( new VariableExpr( ftype->get_parameters().back() ) );
731                }
732                function->get_statements()->get_kids().push_back( new ExprStmt( noLabels, untyped ) );
733                function->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
734        }
735
736        Type * AutogenTupleRoutines::mutate( TupleType * tupleType ) {
737                tupleType = strict_dynamic_cast< TupleType * >( Parent::mutate( tupleType ) );
738                std::string mangleName = SymTab::Mangler::mangleType( tupleType );
739                if ( seenTuples.find( mangleName ) != seenTuples.end() ) return tupleType;
740                seenTuples.insert( mangleName );
741
742                // T ?=?(T *, T);
743                FunctionType *assignType = genAssignType( tupleType );
744
745                // void ?{}(T *); void ^?{}(T *);
746                FunctionType *ctorType = genDefaultType( tupleType );
747                FunctionType *dtorType = genDefaultType( tupleType );
748
749                // void ?{}(T *, T);
750                FunctionType *copyCtorType = genCopyType( tupleType );
751
752                std::set< TypeDecl* > done;
753                std::list< TypeDecl * > typeParams;
754                for ( Type * t : *tupleType ) {
755                        if ( TypeInstType * ty = dynamic_cast< TypeInstType * >( t ) ) {
756                                if ( ! done.count( ty->get_baseType() ) ) {
757                                        TypeDecl * newDecl = new TypeDecl( ty->get_baseType()->get_name(), Type::StorageClasses(), nullptr, TypeDecl::Any );
758                                        TypeInstType * inst = new TypeInstType( Type::Qualifiers(), newDecl->get_name(), newDecl );
759                                        newDecl->get_assertions().push_back( new FunctionDecl( "?=?", Type::StorageClasses(), LinkageSpec::Cforall, genAssignType( inst ), nullptr,
760                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
761                                        newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
762                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
763                                        newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genCopyType( inst ), nullptr,
764                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
765                                        newDecl->get_assertions().push_back( new FunctionDecl( "^?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
766                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
767                                        typeParams.push_back( newDecl );
768                                        done.insert( ty->get_baseType() );
769                                }
770                        }
771                }
772                cloneAll( typeParams, ctorType->get_forall() );
773                cloneAll( typeParams, dtorType->get_forall() );
774                cloneAll( typeParams, copyCtorType->get_forall() );
775                cloneAll( typeParams, assignType->get_forall() );
776
777                FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting );
778                FunctionDecl *ctorDecl = genFunc( "?{}", ctorType, functionNesting );
779                FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting );
780                FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting );
781
782                makeTupleFunctionBody( assignDecl );
783                makeTupleFunctionBody( ctorDecl );
784                makeTupleFunctionBody( copyCtorDecl );
785                makeTupleFunctionBody( dtorDecl );
786
787                addDeclaration( ctorDecl );
788                addDeclaration( copyCtorDecl );
789                addDeclaration( dtorDecl );
790                addDeclaration( assignDecl ); // assignment should come last since it uses copy constructor in return
791
792                return tupleType;
793        }
794
795        DeclarationWithType * AutogenTupleRoutines::mutate( FunctionDecl *functionDecl ) {
796                functionDecl->set_functionType( maybeMutate( functionDecl->get_functionType(), *this ) );
797                functionNesting += 1;
798                functionDecl->set_statements( maybeMutate( functionDecl->get_statements(), *this ) );
799                functionNesting -= 1;
800                return functionDecl;
801        }
802
803        CompoundStmt * AutogenTupleRoutines::mutate( CompoundStmt *compoundStmt ) {
804                seenTuples.beginScope();
805                compoundStmt = strict_dynamic_cast< CompoundStmt * >( Parent::mutate( compoundStmt ) );
806                seenTuples.endScope();
807                return compoundStmt;
808        }
809} // SymTab
810
811// Local Variables: //
812// tab-width: 4 //
813// mode: c++ //
814// compile-command: "make install" //
815// End: //
Note: See TracBrowser for help on using the repository browser.