source: src/SymTab/Autogen.cc @ 5070fe4

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 5070fe4 was 5070fe4, checked in by Aaron Moss <a3moss@…>, 8 years ago

Tweak autogen to treat static-layout generic types like normal structs

  • Property mode set to 100644
File size: 29.5 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Autogen.cc --
8//
9// Author           : Rob Schluntz
10// Created On       : Thu Mar 03 15:45:56 2016
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Tue Jul 12 17:47:17 2016
13// Update Count     : 2
14//
15
16#include <list>
17#include <iterator>
18#include "SynTree/Visitor.h"
19#include "SynTree/Type.h"
20#include "SynTree/Statement.h"
21#include "SynTree/TypeSubstitution.h"
22#include "Common/utility.h"
23#include "AddVisit.h"
24#include "MakeLibCfa.h"
25#include "Autogen.h"
26
27namespace SymTab {
28        class AutogenerateRoutines : public Visitor {
29                public:
30                std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
31
32                virtual void visit( EnumDecl *enumDecl );
33                virtual void visit( StructDecl *structDecl );
34                virtual void visit( UnionDecl *structDecl );
35                virtual void visit( TypeDecl *typeDecl );
36                virtual void visit( TraitDecl *ctxDecl );
37                virtual void visit( FunctionDecl *functionDecl );
38
39                virtual void visit( FunctionType *ftype );
40                virtual void visit( PointerType *ftype );
41
42                virtual void visit( CompoundStmt *compoundStmt );
43                virtual void visit( SwitchStmt *switchStmt );
44
45                AutogenerateRoutines() : functionNesting( 0 ) {}
46                private:
47                template< typename StmtClass > void visitStatement( StmtClass *stmt );
48
49                std::list< Declaration * > declsToAdd;
50                std::set< std::string > structsDone;
51                unsigned int functionNesting;     // current level of nested functions
52        };
53
54        void autogenerateRoutines( std::list< Declaration * > &translationUnit ) {
55                AutogenerateRoutines visitor;
56                acceptAndAdd( translationUnit, visitor, false );
57        }
58
59        bool isUnnamedBitfield( ObjectDecl * obj ) {
60                return obj != NULL && obj->get_name() == "" && obj->get_bitfieldWidth() != NULL;
61        }
62
63        template< typename OutputIterator >
64        void makeScalarFunction( Expression *src, ObjectDecl *dstParam, DeclarationWithType *member, std::string fname, OutputIterator out ) {
65                ObjectDecl *obj = dynamic_cast<ObjectDecl *>( member );
66                // unnamed bit fields are not copied as they cannot be accessed
67                if ( isUnnamedBitfield( obj ) ) return;
68
69                // want to be able to generate assignment, ctor, and dtor generically,
70                // so fname is either ?=?, ?{}, or ^?{}
71                UntypedExpr *fExpr = new UntypedExpr( new NameExpr( fname ) );
72
73                UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
74                derefExpr->get_args().push_back( new VariableExpr( dstParam ) );
75
76                // do something special for unnamed members
77                Expression *dstselect = new AddressExpr( new MemberExpr( member, derefExpr ) );
78                fExpr->get_args().push_back( dstselect );
79
80                if ( src ) {
81                        fExpr->get_args().push_back( src );
82                }
83
84                Statement * callStmt = new ExprStmt( noLabels, fExpr );
85                if ( (fname == "?{}" || fname == "^?{}") && ( !obj || ( obj && obj->get_bitfieldWidth() == NULL ) ) ) {
86                        // implicitly generated ctor/dtor calls should be wrapped
87                        // so that later passes are aware they were generated.
88                        // xxx - don't mark as an implicit ctor/dtor if obj is a bitfield,
89                        // because this causes the address to be taken at codegen, which is illegal in C.
90                        callStmt = new ImplicitCtorDtorStmt( callStmt );
91                }
92                *out++ = callStmt;
93        }
94
95        template< typename OutputIterator >
96        void makeUnionFieldsAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, UnionInstType *unionType, OutputIterator out ) {
97                UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
98                copy->get_args().push_back( new VariableExpr( dstParam ) );
99                copy->get_args().push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
100                copy->get_args().push_back( new SizeofExpr( unionType ) );
101
102                *out++ = new ExprStmt( noLabels, copy );
103        }
104
105        //E ?=?(E volatile*, int),
106        //  ?=?(E _Atomic volatile*, int);
107        void makeEnumFunctions( EnumDecl *enumDecl, EnumInstType *refType, unsigned int functionNesting, std::list< Declaration * > &declsToAdd ) {
108                FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
109
110                ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), refType ), 0 );
111                assignType->get_parameters().push_back( dstParam );
112
113                // void ?{}(E *); void ^?{}(E *);
114                FunctionType * ctorType = assignType->clone();
115                FunctionType * dtorType = assignType->clone();
116
117                ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, refType->clone(), 0 );
118                assignType->get_parameters().push_back( srcParam );
119                // void ?{}(E *, E);
120                FunctionType *copyCtorType = assignType->clone();
121
122                // T ?=?(E *, E);
123                ObjectDecl *returnVal = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, refType->clone(), 0 );
124                assignType->get_returnVals().push_back( returnVal );
125
126                // xxx - should we also generate void ?{}(E *, int) and E ?{}(E *, E)?
127                // right now these cases work, but that might change.
128
129                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
130                // because each unit generates copies of the default routines for each aggregate.
131                // xxx - Temporary: make these functions intrinsic so they codegen as C assignment.
132                // Really they're something of a cross between instrinsic and autogen, so should
133                // probably make a new linkage type
134                FunctionDecl *assignDecl = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, assignType, new CompoundStmt( noLabels ), true, false );
135                FunctionDecl *ctorDecl = new FunctionDecl( "?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, ctorType, new CompoundStmt( noLabels ), true, false );
136                FunctionDecl *copyCtorDecl = new FunctionDecl( "?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, copyCtorType, new CompoundStmt( noLabels ), true, false );
137                FunctionDecl *dtorDecl = new FunctionDecl( "^?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, dtorType, new CompoundStmt( noLabels ), true, false );
138                assignDecl->fixUniqueId();
139                ctorDecl->fixUniqueId();
140                copyCtorDecl->fixUniqueId();
141                dtorDecl->fixUniqueId();
142
143                // enum copy construct and assignment is just C-style assignment.
144                // this looks like a bad recursive call, but code gen will turn it into
145                // a C-style assignment.
146                // This happens before function pointer type conversion, so need to do it manually here
147                VariableExpr * assignVarExpr = new VariableExpr( assignDecl );
148                Type *& assignVarExprType = assignVarExpr->get_results().front();
149                assignVarExprType = new PointerType( Type::Qualifiers(), assignVarExprType );
150                ApplicationExpr * assignExpr = new ApplicationExpr( assignVarExpr );
151                assignExpr->get_args().push_back( new VariableExpr( dstParam ) );
152                assignExpr->get_args().push_back( new VariableExpr( srcParam ) );
153
154                // body is either return stmt or expr stmt
155                assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, assignExpr ) );
156                copyCtorDecl->get_statements()->get_kids().push_back( new ExprStmt( noLabels, assignExpr->clone() ) );
157
158                declsToAdd.push_back( assignDecl );
159                declsToAdd.push_back( ctorDecl );
160                declsToAdd.push_back( copyCtorDecl );
161                declsToAdd.push_back( dtorDecl );
162        }
163
164        /// Clones a reference type, replacing any parameters it may have with a clone of the provided list
165        template< typename GenericInstType >
166        GenericInstType *cloneWithParams( GenericInstType *refType, const std::list< Expression* >& params ) {
167                GenericInstType *clone = refType->clone();
168                clone->get_parameters().clear();
169                cloneAll( params, clone->get_parameters() );
170                return clone;
171        }
172
173        /// Creates a new type decl that's the same as src, but renamed and with only the ?=?, ?{} (default and copy), and ^?{} assertions (for complete types only)
174        TypeDecl *cloneAndRename( TypeDecl *src, const std::string &name ) {
175                // TypeDecl *dst = new TypeDecl( name, src->get_storageClass(), 0, src->get_kind() );
176
177                // if ( src->get_kind() == TypeDecl::Any ) {
178                //      TypeInstType *opParamType = new TypeInstType( Type::Qualifiers(), name, dst );
179                //      FunctionType *opFunctionType = new FunctionType( Type::Qualifiers(), false );
180                //      opFunctionType->get_parameters().push_back(
181                //              new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), opParamType->clone() ), 0 ) );
182                //      FunctionDecl *ctorAssert = new FunctionDecl( "?{}", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, opFunctionType->clone(), 0, false, false );
183                //      FunctionDecl *dtorAssert = new FunctionDecl( "^?{}", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, opFunctionType->clone(), 0, false, false );
184
185                //      opFunctionType->get_parameters().push_back(
186                //              new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, opParamType, 0 ) );
187                //      FunctionDecl *copyCtorAssert = new FunctionDecl( "?{}", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, opFunctionType->clone(), 0, false, false );
188
189                //      opFunctionType->get_returnVals().push_back(
190                //              new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, opParamType->clone(), 0 ) );
191                //      FunctionDecl *assignAssert = new FunctionDecl( "?=?", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, opFunctionType, 0, false, false );
192
193
194                //      dst->get_assertions().push_back( assignAssert );
195                //      dst->get_assertions().push_back( ctorAssert );
196                //      dst->get_assertions().push_back( dtorAssert );
197                //      dst->get_assertions().push_back( copyCtorAssert );
198                // }
199
200                TypeDecl *dst = new TypeDecl( src->get_name(), src->get_storageClass(), 0, src->get_kind() );
201                cloneAll(src->get_assertions(), dst->get_assertions());
202                return dst;
203        }
204
205        void makeStructMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, TypeSubstitution & genericSubs, bool isGeneric, bool isDynamicLayout, bool forward = true ) {
206                if ( isGeneric ) {
207                        // rewrite member type in terms of the type variables on this operator
208                        field = field->clone();
209                        genericSubs.apply( field );
210
211                        if ( src ) {
212                                genericSubs.apply( src );
213                        }
214                }
215
216                ObjectDecl * returnVal = NULL;
217                if ( ! func->get_functionType()->get_returnVals().empty() ) {
218                        returnVal = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_returnVals().front() );
219                }
220
221                // assign to destination (and return value if generic)
222                if ( ArrayType *array = dynamic_cast< ArrayType * >( field->get_type() ) ) {
223                        UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
224                        derefExpr->get_args().push_back( new VariableExpr( dstParam ) );
225                        Expression *dstselect = new MemberExpr( field, derefExpr );
226
227                        makeArrayFunction( src, dstselect, array, func->get_name(), back_inserter( func->get_statements()->get_kids() ), forward );
228                        if ( isDynamicLayout && returnVal ) {
229                                UntypedExpr *derefRet = new UntypedExpr( new NameExpr( "*?" ) );
230                                derefRet->get_args().push_back( new VariableExpr( returnVal ) );
231                                Expression *retselect = new MemberExpr( field, derefRet );
232
233                                makeArrayFunction( src, retselect, array, func->get_name(), back_inserter( func->get_statements()->get_kids() ), forward );
234                        }
235                } else {
236                        makeScalarFunction( src, dstParam, field, func->get_name(), back_inserter( func->get_statements()->get_kids() ) );
237                        if ( isDynamicLayout && returnVal ) makeScalarFunction( src, returnVal, field, func->get_name(), back_inserter( func->get_statements()->get_kids() ) );
238                } // if
239        }
240
241        template<typename Iterator>
242        void makeStructFunctionBody( Iterator member, Iterator end, FunctionDecl * func, TypeSubstitution & genericSubs, bool isGeneric, bool isDynamicLayout, bool forward = true ) {
243                for ( ; member != end; ++member ) {
244                        if ( DeclarationWithType *field = dynamic_cast< DeclarationWithType * >( *member ) ) { // otherwise some form of type declaration, e.g. Aggregate
245                                // query the type qualifiers of this field and skip assigning it if it is marked const.
246                                // If it is an array type, we need to strip off the array layers to find its qualifiers.
247                                Type * type = field->get_type();
248                                while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
249                                        type = at->get_base();
250                                }
251
252                                if ( type->get_qualifiers().isConst && func->get_name() == "?=?" ) {
253                                        // don't assign const members, but do construct/destruct
254                                        continue;
255                                }
256
257                                if ( field->get_name() == "" ) {
258                                        // don't assign to anonymous members
259                                        // xxx - this is a temporary fix. Anonymous members tie into
260                                        // our inheritance model. I think the correct way to handle this is to
261                                        // cast the structure to the type of the member and let the resolver
262                                        // figure out whether it's valid and have a pass afterwards that fixes
263                                        // the assignment to use pointer arithmetic with the offset of the
264                                        // member, much like how generic type members are handled.
265                                        continue;
266                                }
267
268                                assert( ! func->get_functionType()->get_parameters().empty() );
269                                ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().front() );
270                                ObjectDecl * srcParam = NULL;
271                                if ( func->get_functionType()->get_parameters().size() == 2 ) {
272                                        srcParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().back() );
273                                }
274                                // srcParam may be NULL, in which case we have default ctor/dtor
275                                assert( dstParam );
276
277                                Expression *srcselect = srcParam ? new MemberExpr( field, new VariableExpr( srcParam ) ) : NULL;
278                                makeStructMemberOp( dstParam, srcselect, field, func, genericSubs, isGeneric, isDynamicLayout, forward );
279                        } // if
280                } // for
281        } // makeStructFunctionBody
282
283        /// generate the body of a constructor which takes parameters that match fields, e.g.
284        /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
285        template<typename Iterator>
286        void makeStructFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func, TypeSubstitution & genericSubs, bool isGeneric, bool isDynamicLayout ) {
287                FunctionType * ftype = func->get_functionType();
288                std::list<DeclarationWithType*> & params = ftype->get_parameters();
289                assert( params.size() >= 2 );  // should not call this function for default ctor, etc.
290
291                // skip 'this' parameter
292                ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( params.front() );
293                assert( dstParam );
294                std::list<DeclarationWithType*>::iterator parameter = params.begin()+1;
295                for ( ; member != end; ++member ) {
296                        if ( DeclarationWithType * field = dynamic_cast<DeclarationWithType*>( *member ) ) {
297                                if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
298                                        // don't make a function whose parameter is an unnamed bitfield
299                                        continue;
300                                } else if ( field->get_name() == "" ) {
301                                        // don't assign to anonymous members
302                                        // xxx - this is a temporary fix. Anonymous members tie into
303                                        // our inheritance model. I think the correct way to handle this is to
304                                        // cast the structure to the type of the member and let the resolver
305                                        // figure out whether it's valid and have a pass afterwards that fixes
306                                        // the assignment to use pointer arithmetic with the offset of the
307                                        // member, much like how generic type members are handled.
308                                        continue;
309                                } else if ( parameter != params.end() ) {
310                                        // matching parameter, initialize field with copy ctor
311                                        Expression *srcselect = new VariableExpr(*parameter);
312                                        makeStructMemberOp( dstParam, srcselect, field, func, genericSubs, isGeneric, isDynamicLayout );
313                                        ++parameter;
314                                } else {
315                                        // no matching parameter, initialize field with default ctor
316                                        makeStructMemberOp( dstParam, NULL, field, func, genericSubs, isGeneric, isDynamicLayout );
317                                }
318                        }
319                }
320        }
321
322        void makeStructFunctions( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting, std::list< Declaration * > & declsToAdd ) {
323                FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
324
325                // Make function polymorphic in same parameters as generic struct, if applicable
326                bool isGeneric = false;  // NOTE this flag is an incredibly ugly kludge; we should fix the assignment signature instead (ditto for union)
327                bool isDynamicLayout = false;  // NOTE see above re: kludge
328                std::list< TypeDecl* >& genericParams = aggregateDecl->get_parameters();
329                std::list< Expression* > structParams;  // List of matching parameters to put on types
330                TypeSubstitution genericSubs; // Substitutions to make to member types of struct
331                for ( std::list< TypeDecl* >::const_iterator param = genericParams.begin(); param != genericParams.end(); ++param ) {
332                        isGeneric = true;
333                        if ( (*param)->get_kind() == TypeDecl::Any ) isDynamicLayout = true;
334                        TypeDecl *typeParam = cloneAndRename( *param, "_autoassign_" + aggregateDecl->get_name() + "_" + (*param)->get_name() );
335                        assignType->get_forall().push_back( typeParam );
336                        TypeInstType *newParamType = new TypeInstType( Type::Qualifiers(), typeParam->get_name(), typeParam );
337                        genericSubs.add( (*param)->get_name(), newParamType );
338                        structParams.push_back( new TypeExpr( newParamType ) );
339                }
340
341                ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), cloneWithParams( refType, structParams ) ), 0 );
342                assignType->get_parameters().push_back( dstParam );
343
344                // void ?{}(T *); void ^?{}(T *);
345                FunctionType *ctorType = assignType->clone();
346                FunctionType *dtorType = assignType->clone();
347
348                ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, structParams ), 0 );
349                assignType->get_parameters().push_back( srcParam );
350
351                // void ?{}(T *, T);
352                FunctionType *copyCtorType = assignType->clone();
353
354                // T ?=?(T *, T);
355                ObjectDecl *returnVal = new ObjectDecl( "_ret", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, structParams ), 0 );
356                assignType->get_returnVals().push_back( returnVal );
357
358                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
359                // because each unit generates copies of the default routines for each aggregate.
360                FunctionDecl *assignDecl = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true, false );
361                FunctionDecl *ctorDecl = new FunctionDecl( "?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, ctorType, new CompoundStmt( noLabels ), true, false );
362                FunctionDecl *copyCtorDecl = new FunctionDecl( "?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, copyCtorType, new CompoundStmt( noLabels ), true, false );
363                FunctionDecl *dtorDecl = new FunctionDecl( "^?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, dtorType, new CompoundStmt( noLabels ), true, false );
364                assignDecl->fixUniqueId();
365                ctorDecl->fixUniqueId();
366                copyCtorDecl->fixUniqueId();
367                dtorDecl->fixUniqueId();
368
369                // create constructors which take each member type as a parameter.
370                // for example, for struct A { int x, y; }; generate
371                // void ?{}(A *, int) and void ?{}(A *, int, int)
372                std::list<Declaration *> memCtors;
373                FunctionType * memCtorType = ctorType->clone();
374                for ( std::list<Declaration *>::iterator i = aggregateDecl->get_members().begin(); i != aggregateDecl->get_members().end(); ++i ) {
375                        DeclarationWithType * member = dynamic_cast<DeclarationWithType *>( *i );
376                        assert( member );
377                        if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( member ) ) ) {
378                                // don't make a function whose parameter is an unnamed bitfield
379                                continue;
380                        } else if ( member->get_name() == "" ) {
381                                // don't assign to anonymous members
382                                // xxx - this is a temporary fix. Anonymous members tie into
383                                // our inheritance model. I think the correct way to handle this is to
384                                // cast the structure to the type of the member and let the resolver
385                                // figure out whether it's valid and have a pass afterwards that fixes
386                                // the assignment to use pointer arithmetic with the offset of the
387                                // member, much like how generic type members are handled.
388                                continue;
389                        }
390                        memCtorType->get_parameters().push_back( new ObjectDecl( member->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, member->get_type()->clone(), 0 ) );
391                        FunctionDecl * ctor = new FunctionDecl( "?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, memCtorType->clone(), new CompoundStmt( noLabels ), true, false );
392                        ctor->fixUniqueId();
393                        makeStructFieldCtorBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), ctor, genericSubs, isGeneric, isDynamicLayout );
394                        memCtors.push_back( ctor );
395                }
396                delete memCtorType;
397
398                // generate appropriate calls to member ctor, assignment
399                makeStructFunctionBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), assignDecl, genericSubs, isGeneric, isDynamicLayout );
400                makeStructFunctionBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), ctorDecl, genericSubs, isGeneric, isDynamicLayout );
401                makeStructFunctionBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), copyCtorDecl, genericSubs, isGeneric, isDynamicLayout );
402                // needs to do everything in reverse, so pass "forward" as false
403                makeStructFunctionBody( aggregateDecl->get_members().rbegin(), aggregateDecl->get_members().rend(), dtorDecl, genericSubs, isGeneric, isDynamicLayout, false );
404
405                if ( ! isGeneric ) assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
406
407                declsToAdd.push_back( assignDecl );
408                declsToAdd.push_back( ctorDecl );
409                declsToAdd.push_back( copyCtorDecl );
410                declsToAdd.push_back( dtorDecl );
411                declsToAdd.splice( declsToAdd.end(), memCtors );
412        }
413
414        void makeUnionFunctions( UnionDecl *aggregateDecl, UnionInstType *refType, unsigned int functionNesting, std::list< Declaration * > & declsToAdd ) {
415                FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
416
417                // Make function polymorphic in same parameters as generic union, if applicable
418                bool isDynamicLayout = false; // NOTE this flag is an incredibly ugly kludge; we should fix the assignment signature instead (ditto for struct)
419                std::list< TypeDecl* >& genericParams = aggregateDecl->get_parameters();
420                std::list< Expression* > unionParams;  // List of matching parameters to put on types
421                for ( std::list< TypeDecl* >::const_iterator param = genericParams.begin(); param != genericParams.end(); ++param ) {
422                        if ( (*param)->get_kind() == TypeDecl::Any ) isDynamicLayout = true;
423                        TypeDecl *typeParam = cloneAndRename( *param, "_autoassign_" + aggregateDecl->get_name() + "_" + (*param)->get_name() );
424                        assignType->get_forall().push_back( typeParam );
425                        unionParams.push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeParam->get_name(), typeParam ) ) );
426                }
427
428                ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), cloneWithParams( refType, unionParams ) ), 0 );
429                assignType->get_parameters().push_back( dstParam );
430
431                // default ctor/dtor need only first parameter
432                FunctionType * ctorType = assignType->clone();
433                FunctionType * dtorType = assignType->clone();
434
435                ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, unionParams ), 0 );
436                assignType->get_parameters().push_back( srcParam );
437
438                // copy ctor needs both parameters
439                FunctionType * copyCtorType = assignType->clone();
440
441                // assignment needs both and return value
442                ObjectDecl *returnVal = new ObjectDecl( "_ret", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, unionParams ), 0 );
443                assignType->get_returnVals().push_back( returnVal );
444
445                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
446                // because each unit generates copies of the default routines for each aggregate.
447                FunctionDecl *assignDecl = new FunctionDecl( "?=?",  functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true, false );
448                FunctionDecl *ctorDecl = new FunctionDecl( "?{}",  functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, ctorType, new CompoundStmt( noLabels ), true, false );
449                FunctionDecl *copyCtorDecl = new FunctionDecl( "?{}",  functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, copyCtorType, NULL, true, false );
450                FunctionDecl *dtorDecl = new FunctionDecl( "^?{}",  functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, dtorType, new CompoundStmt( noLabels ), true, false );
451
452                assignDecl->fixUniqueId();
453                ctorDecl->fixUniqueId();
454                copyCtorDecl->fixUniqueId();
455                dtorDecl->fixUniqueId();
456
457                makeUnionFieldsAssignment( srcParam, dstParam, cloneWithParams( refType, unionParams ), back_inserter( assignDecl->get_statements()->get_kids() ) );
458                if ( isDynamicLayout ) makeUnionFieldsAssignment( srcParam, returnVal, cloneWithParams( refType, unionParams ), back_inserter( assignDecl->get_statements()->get_kids() ) );
459                else assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
460
461                // body of assignment and copy ctor is the same
462                copyCtorDecl->set_statements( assignDecl->get_statements()->clone() );
463
464                declsToAdd.push_back( assignDecl );
465                declsToAdd.push_back( ctorDecl );
466                declsToAdd.push_back( copyCtorDecl );
467                declsToAdd.push_back( dtorDecl );
468        }
469
470        void AutogenerateRoutines::visit( EnumDecl *enumDecl ) {
471                if ( ! enumDecl->get_members().empty() ) {
472                        EnumInstType *enumInst = new EnumInstType( Type::Qualifiers(), enumDecl->get_name() );
473                        // enumInst->set_baseEnum( enumDecl );
474                        // declsToAdd.push_back(
475                        makeEnumFunctions( enumDecl, enumInst, functionNesting, declsToAdd );
476                }
477        }
478
479        void AutogenerateRoutines::visit( StructDecl *structDecl ) {
480                if ( ! structDecl->get_members().empty() && structsDone.find( structDecl->get_name() ) == structsDone.end() ) {
481                        StructInstType structInst( Type::Qualifiers(), structDecl->get_name() );
482                        structInst.set_baseStruct( structDecl );
483                        makeStructFunctions( structDecl, &structInst, functionNesting, declsToAdd );
484                        structsDone.insert( structDecl->get_name() );
485                } // if
486        }
487
488        void AutogenerateRoutines::visit( UnionDecl *unionDecl ) {
489                if ( ! unionDecl->get_members().empty() ) {
490                        UnionInstType unionInst( Type::Qualifiers(), unionDecl->get_name() );
491                        unionInst.set_baseUnion( unionDecl );
492                        makeUnionFunctions( unionDecl, &unionInst, functionNesting, declsToAdd );
493                } // if
494        }
495
496        void AutogenerateRoutines::visit( TypeDecl *typeDecl ) {
497                CompoundStmt *stmts = 0;
498                TypeInstType *typeInst = new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), false );
499                typeInst->set_baseType( typeDecl );
500                ObjectDecl *src = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, typeInst->clone(), 0 );
501                ObjectDecl *dst = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), typeInst->clone() ), 0 );
502                if ( typeDecl->get_base() ) {
503                        // xxx - generate ctor/dtors for typedecls, e.g.
504                        // otype T = int *;
505                        stmts = new CompoundStmt( std::list< Label >() );
506                        UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
507                        assign->get_args().push_back( new CastExpr( new VariableExpr( dst ), new PointerType( Type::Qualifiers(), typeDecl->get_base()->clone() ) ) );
508                        assign->get_args().push_back( new CastExpr( new VariableExpr( src ), typeDecl->get_base()->clone() ) );
509                        stmts->get_kids().push_back( new ReturnStmt( std::list< Label >(), assign ) );
510                } // if
511                FunctionType *type = new FunctionType( Type::Qualifiers(), false );
512                type->get_returnVals().push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, typeInst, 0 ) );
513                type->get_parameters().push_back( dst );
514                type->get_parameters().push_back( src );
515                FunctionDecl *func = new FunctionDecl( "?=?", DeclarationNode::NoStorageClass, LinkageSpec::AutoGen, type, stmts, true, false );
516                declsToAdd.push_back( func );
517        }
518
519        void addDecls( std::list< Declaration * > &declsToAdd, std::list< Statement * > &statements, std::list< Statement * >::iterator i ) {
520                for ( std::list< Declaration * >::iterator decl = declsToAdd.begin(); decl != declsToAdd.end(); ++decl ) {
521                        statements.insert( i, new DeclStmt( noLabels, *decl ) );
522                } // for
523                declsToAdd.clear();
524        }
525
526        void AutogenerateRoutines::visit( FunctionType *) {
527                // ensure that we don't add assignment ops for types defined as part of the function
528        }
529
530        void AutogenerateRoutines::visit( PointerType *) {
531                // ensure that we don't add assignment ops for types defined as part of the pointer
532        }
533
534        void AutogenerateRoutines::visit( TraitDecl *) {
535                // ensure that we don't add assignment ops for types defined as part of the trait
536        }
537
538        template< typename StmtClass >
539        inline void AutogenerateRoutines::visitStatement( StmtClass *stmt ) {
540                std::set< std::string > oldStructs = structsDone;
541                addVisit( stmt, *this );
542                structsDone = oldStructs;
543        }
544
545        void AutogenerateRoutines::visit( FunctionDecl *functionDecl ) {
546                maybeAccept( functionDecl->get_functionType(), *this );
547                acceptAll( functionDecl->get_oldDecls(), *this );
548                functionNesting += 1;
549                maybeAccept( functionDecl->get_statements(), *this );
550                functionNesting -= 1;
551        }
552
553        void AutogenerateRoutines::visit( CompoundStmt *compoundStmt ) {
554                visitStatement( compoundStmt );
555        }
556
557        void AutogenerateRoutines::visit( SwitchStmt *switchStmt ) {
558                visitStatement( switchStmt );
559        }
560} // SymTab
Note: See TracBrowser for help on using the repository browser.