source: src/SymTab/Autogen.cc @ ea6332d

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 ea6332d was d180746, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Big header cleaning pass - commit 2

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