source: src/SymTab/Autogen.cc @ 8804701

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 8804701 was 207c7e1d, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

disable autogeneration of ctor/dtor/assign when a member's corresponding operation is missing

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