source: src/SymTab/Autogen.cc @ 83a071f9

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 83a071f9 was 46adb83, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Add unused attribute to union ctor/dtor parameters to silence warnings

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