source: src/SymTab/Autogen.cc @ c6e2c18

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since c6e2c18 was c6e2c18, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Merge branch 'master' into cleanup-dtors

  • Property mode set to 100644
File size: 33.6 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Autogen.cc --
8//
9// Author           : Rob Schluntz
10// Created On       : Thu Mar 03 15:45:56 2016
11// Last Modified By : Andrew Beach
12// Last Modified On : Fri Jul 14 16:41:00 2017
13// Update Count     : 62
14//
15
16#include "Autogen.h"
17
18#include <algorithm>               // for count_if
19#include <cassert>                 // for strict_dynamic_cast, assert, assertf
20#include <iterator>                // for back_insert_iterator, back_inserter
21#include <list>                    // for list, _List_iterator, list<>::iter...
22#include <set>                     // for set, _Rb_tree_const_iterator
23#include <utility>                 // for pair
24#include <vector>                  // for vector
25
26#include "AddVisit.h"              // for addVisit
27#include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
28#include "Common/PassVisitor.h"    // for PassVisitor
29#include "Common/ScopedMap.h"      // for ScopedMap<>::const_iterator, Scope...
30#include "Common/utility.h"        // for cloneAll, operator+
31#include "GenPoly/ScopedSet.h"     // for ScopedSet, ScopedSet<>::iterator
32#include "InitTweak/GenInit.h"     // for fixReturnStatements
33#include "ResolvExpr/Resolver.h"   // for resolveDecl
34#include "SymTab/Mangler.h"        // for Mangler
35#include "SynTree/Attribute.h"     // For Attribute
36#include "SynTree/Mutator.h"       // for maybeMutate
37#include "SynTree/Statement.h"     // for CompoundStmt, ReturnStmt, ExprStmt
38#include "SynTree/Type.h"          // for FunctionType, Type, TypeInstType
39#include "SynTree/Visitor.h"       // for maybeAccept, Visitor, acceptAll
40
41class Attribute;
42
43namespace SymTab {
44        Type * SizeType = 0;
45
46        /// Data used to generate functions generically. Specifically, the name of the generated function and a function which generates the routine protoype
47        struct FuncData {
48                typedef FunctionType * (*TypeGen)( Type *, bool );
49                FuncData( const std::string & fname, const TypeGen & genType ) : fname( fname ), genType( genType ) {}
50                std::string fname;
51                TypeGen genType;
52        };
53
54        struct AutogenerateRoutines final : public WithDeclsToAdd, public WithVisitorRef<AutogenerateRoutines>, public WithGuards, public WithShortCircuiting, public WithIndexer {
55                AutogenerateRoutines();
56
57                void previsit( EnumDecl * enumDecl );
58                void previsit( StructDecl * structDecl );
59                void previsit( UnionDecl * structDecl );
60                void previsit( TypeDecl * typeDecl );
61                void previsit( TraitDecl * traitDecl );
62                void previsit( FunctionDecl * functionDecl );
63
64                void previsit( CompoundStmt * compoundStmt );
65
66          private:
67
68                GenPoly::ScopedSet< std::string > structsDone;
69                unsigned int functionNesting = 0;     // current level of nested functions
70
71                std::vector< FuncData > data;
72        };
73
74        /// generates routines for tuple types.
75        struct AutogenTupleRoutines : public WithDeclsToAdd, public WithVisitorRef<AutogenTupleRoutines>, public WithGuards, public WithShortCircuiting {
76                void previsit( FunctionDecl * functionDecl );
77
78                void postvisit( TupleType * tupleType );
79
80                void previsit( CompoundStmt * compoundStmt );
81
82          private:
83                unsigned int functionNesting = 0;     // current level of nested functions
84                GenPoly::ScopedSet< std::string > seenTuples;
85        };
86
87        void autogenerateRoutines( std::list< Declaration * > &translationUnit ) {
88                PassVisitor<AutogenerateRoutines> generator;
89                acceptAll( translationUnit, generator );
90
91                // needs to be done separately because AutogenerateRoutines skips types that appear as function arguments, etc.
92                // AutogenTupleRoutines tupleGenerator;
93                // acceptAll( translationUnit, tupleGenerator );
94        }
95
96        //=============================================================================================
97        // FuncGenerator definitions
98        //=============================================================================================
99        class FuncGenerator {
100        public:
101                std::list< Declaration * > definitions, forwards;
102
103                FuncGenerator( Type * type, const std::vector< FuncData > & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : type( type ), data( data ), functionNesting( functionNesting ), indexer( indexer ) {}
104
105                virtual bool shouldAutogen() const = 0;
106                void genStandardFuncs();
107                virtual void genFieldCtors() = 0;
108        protected:
109                Type * type;
110                const std::vector< FuncData > & data;
111                unsigned int functionNesting;
112                SymTab::Indexer & indexer;
113
114                virtual void genFuncBody( FunctionDecl * dcl ) = 0;
115                virtual bool isConcurrentType() const = 0;
116
117                void resolve( FunctionDecl * dcl );
118                void generatePrototypes( std::list< FunctionDecl * > & newFuncs );
119        };
120
121        class StructFuncGenerator : public FuncGenerator {
122                StructDecl * aggregateDecl;
123        public:
124                StructFuncGenerator( StructDecl * aggregateDecl, StructInstType * refType, const std::vector< FuncData > & data,  unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), aggregateDecl( aggregateDecl) {}
125
126                virtual bool shouldAutogen() const override;
127                virtual bool isConcurrentType() const override;
128
129                virtual void genFuncBody( FunctionDecl * dcl ) override;
130                virtual void genFieldCtors() override;
131
132        private:
133                /// generates a single struct member operation (constructor call, destructor call, assignment call)
134                void makeMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, bool forward = true );
135
136                /// 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
137                template<typename Iterator>
138                void makeFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward = true );
139
140                /// generate the body of a constructor which takes parameters that match fields, e.g.
141                /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
142                template<typename Iterator>
143                void makeFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func );
144        };
145
146        class UnionFuncGenerator : public FuncGenerator {
147                UnionDecl * aggregateDecl;
148        public:
149                UnionFuncGenerator( UnionDecl * aggregateDecl, UnionInstType * refType, const std::vector< FuncData > & data,  unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), aggregateDecl( aggregateDecl) {}
150
151                virtual bool shouldAutogen() const override;
152                virtual bool isConcurrentType() const override;
153
154                virtual void genFuncBody( FunctionDecl * dcl ) override;
155                virtual void genFieldCtors() override;
156
157        private:
158                /// generates a single struct member operation (constructor call, destructor call, assignment call)
159                template<typename OutputIterator>
160                void makeMemberOp( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out );
161
162                /// 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
163                template<typename Iterator>
164                void makeFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward = true );
165
166                /// generate the body of a constructor which takes parameters that match fields, e.g.
167                /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
168                template<typename Iterator>
169                void makeFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func );
170        };
171
172        class EnumFuncGenerator : public FuncGenerator {
173        public:
174                EnumFuncGenerator( EnumInstType * refType, const std::vector< FuncData > & data,  unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ) {}
175
176                virtual bool shouldAutogen() const override;
177                virtual bool isConcurrentType() const override;
178
179                virtual void genFuncBody( FunctionDecl * dcl ) override;
180                virtual void genFieldCtors() override;
181
182        private:
183        };
184
185        class TypeFuncGenerator : public FuncGenerator {
186                TypeDecl * typeDecl;
187        public:
188                TypeFuncGenerator( TypeDecl * typeDecl, TypeInstType * refType, const std::vector<FuncData> & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), typeDecl( typeDecl ) {}
189
190                virtual bool shouldAutogen() const override;
191                virtual void genFuncBody( FunctionDecl * dcl ) override;
192                virtual bool isConcurrentType() const override;
193                virtual void genFieldCtors() override;
194        };
195
196        //=============================================================================================
197        // helper functions
198        //=============================================================================================
199        void generateFunctions( FuncGenerator & gen, std::list< Declaration * > & declsToAdd ) {
200                if ( ! gen.shouldAutogen() ) return;
201
202                // generate each of the functions based on the supplied FuncData objects
203                gen.genStandardFuncs();
204                gen.genFieldCtors();
205
206                declsToAdd.splice( declsToAdd.end(), gen.forwards );
207                declsToAdd.splice( declsToAdd.end(), gen.definitions );
208        }
209
210        bool isUnnamedBitfield( ObjectDecl * obj ) {
211                return obj != nullptr && obj->name == "" && obj->bitfieldWidth != nullptr;
212        }
213
214        /// inserts a forward declaration for functionDecl into declsToAdd
215        void addForwardDecl( FunctionDecl * functionDecl, std::list< Declaration * > & declsToAdd ) {
216                FunctionDecl * decl = functionDecl->clone();
217                delete decl->statements;
218                decl->statements = nullptr;
219                declsToAdd.push_back( decl );
220                decl->fixUniqueId();
221        }
222
223        const std::list< TypeDecl * > getGenericParams( Type * t ) {
224                std::list< TypeDecl * > * ret = nullptr;
225                if ( StructInstType * inst = dynamic_cast< StructInstType * > ( t ) ) {
226                        ret = inst->get_baseParameters();
227                } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( t ) ) {
228                        ret = inst->get_baseParameters();
229                }
230                return ret ? *ret : std::list< TypeDecl * >();
231        }
232
233        /// given type T, generate type of default ctor/dtor, i.e. function type void (*) (T *)
234        FunctionType * genDefaultType( Type * paramType, bool maybePolymorphic ) {
235                FunctionType *ftype = new FunctionType( Type::Qualifiers(), false );
236                if ( maybePolymorphic ) {
237                        // only copy in
238                        const auto & typeParams = getGenericParams( paramType );
239                        cloneAll( typeParams, ftype->forall );
240                }
241                ObjectDecl *dstParam = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new ReferenceType( Type::Qualifiers(), paramType->clone() ), nullptr );
242                ftype->parameters.push_back( dstParam );
243                return ftype;
244        }
245
246        /// given type T, generate type of copy ctor, i.e. function type void (*) (T *, T)
247        FunctionType * genCopyType( Type * paramType, bool maybePolymorphic ) {
248                FunctionType *ftype = genDefaultType( paramType, maybePolymorphic );
249                ObjectDecl *srcParam = new ObjectDecl( "_src", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
250                ftype->parameters.push_back( srcParam );
251                return ftype;
252        }
253
254        /// given type T, generate type of assignment, i.e. function type T (*) (T *, T)
255        FunctionType * genAssignType( Type * paramType, bool maybePolymorphic ) {
256                FunctionType *ftype = genCopyType( paramType, maybePolymorphic );
257                ObjectDecl *returnVal = new ObjectDecl( "_ret", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
258                ftype->returnVals.push_back( returnVal );
259                return ftype;
260        }
261
262        /// generate a function decl from a name and type. Nesting depth determines whether
263        /// the declaration is static or not; optional paramter determines if declaration is intrinsic
264        FunctionDecl * genFunc( const std::string & fname, FunctionType * ftype, unsigned int functionNesting, bool isIntrinsic = false  ) {
265                // Routines at global scope marked "static" to prevent multiple definitions in separate translation units
266                // because each unit generates copies of the default routines for each aggregate.
267                Type::StorageClasses scs = functionNesting > 0 ? Type::StorageClasses() : Type::StorageClasses( Type::Static );
268                LinkageSpec::Spec spec = isIntrinsic ? LinkageSpec::Intrinsic : LinkageSpec::AutoGen;
269                FunctionDecl * decl = new FunctionDecl( fname, scs, spec, ftype, new CompoundStmt( noLabels ),
270                                                                                                std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) );
271                decl->fixUniqueId();
272                return decl;
273        }
274
275        Type * declToType( Declaration * decl ) {
276                if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( decl ) ) {
277                        return dwt->get_type();
278                }
279                return nullptr;
280        }
281
282        Type * declToTypeDeclBase( Declaration * decl ) {
283                if ( TypeDecl * td = dynamic_cast< TypeDecl * >( decl ) ) {
284                        return td->base;
285                }
286                return nullptr;
287        }
288
289        //=============================================================================================
290        // FuncGenerator member definitions
291        //=============================================================================================
292        void FuncGenerator::genStandardFuncs() {
293                std::list< FunctionDecl * > newFuncs;
294                generatePrototypes( newFuncs );
295
296                for ( FunctionDecl * dcl : newFuncs ) {
297                        genFuncBody( dcl );
298                        if ( CodeGen::isAssignment( dcl->name ) ) {
299                                // assignment needs to return a value
300                                FunctionType * assignType = dcl->type;
301                                assert( assignType->parameters.size() == 2 );
302                                assert( assignType->returnVals.size() == 1 );
303                                ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( assignType->parameters.front() );
304                                dcl->statements->push_back( new ReturnStmt( noLabels, new VariableExpr( dstParam ) ) );
305                        }
306                        resolve( dcl );
307                }
308        }
309
310        void FuncGenerator::generatePrototypes( std::list< FunctionDecl * > & newFuncs ) {
311                bool concurrent_type = isConcurrentType();
312                for ( const FuncData & d : data ) {
313                        // generate a function (?{}, ?=?, ^?{}) based on the current FuncData.
314                        FunctionType * ftype = d.genType( type, true );
315
316                        // destructor for concurrent type must be mutex
317                        if ( concurrent_type && CodeGen::isDestructor( d.fname ) ) {
318                                ftype->parameters.front()->get_type()->set_mutex( true );
319                        }
320
321                        newFuncs.push_back( genFunc( d.fname, ftype, functionNesting ) );
322                }
323        }
324
325        void FuncGenerator::resolve( FunctionDecl * dcl ) {
326                try {
327                        ResolvExpr::resolveDecl( dcl, indexer );
328                        if ( functionNesting == 0 ) {
329                                // forward declare if top-level struct, so that
330                                // type is complete as soon as its body ends
331                                // Note: this is necessary if we want structs which contain
332                                // generic (otype) structs as members.
333                                addForwardDecl( dcl, forwards );
334                        }
335                        definitions.push_back( dcl );
336                        indexer.addId( dcl );
337                } catch ( SemanticError err ) {
338                        // okay if decl does not resolve - that means the function should not be generated
339                        delete dcl;
340                }
341        }
342
343        bool StructFuncGenerator::shouldAutogen() const {
344                // Builtins do not use autogeneration.
345                return ! aggregateDecl->linkage.is_builtin;
346        }
347        bool StructFuncGenerator::isConcurrentType() const { return aggregateDecl->is_thread() || aggregateDecl->is_monitor(); }
348
349        void StructFuncGenerator::genFuncBody( FunctionDecl * dcl ) {
350                // generate appropriate calls to member ctor, assignment
351                // destructor needs to do everything in reverse, so pass "forward" based on whether the function is a destructor
352                if ( ! CodeGen::isDestructor( dcl->name ) ) {
353                        makeFunctionBody( aggregateDecl->members.begin(), aggregateDecl->members.end(), dcl );
354                } else {
355                        makeFunctionBody( aggregateDecl->members.rbegin(), aggregateDecl->members.rend(), dcl, false );
356                }
357        }
358
359        void StructFuncGenerator::genFieldCtors() {
360                // field ctors are only generated if default constructor and copy constructor are both generated
361                unsigned numCtors = std::count_if( definitions.begin(), definitions.end(), [](Declaration * dcl) { return CodeGen::isConstructor( dcl->name ); } );
362
363                // Field constructors are only generated if default and copy constructor
364                // are generated, since they need access to both
365                if ( numCtors != 2 ) return;
366
367                // create constructors which take each member type as a parameter.
368                // for example, for struct A { int x, y; }; generate
369                //   void ?{}(A *, int) and void ?{}(A *, int, int)
370                FunctionType * memCtorType = genDefaultType( type );
371                for ( Declaration * member : aggregateDecl->members ) {
372                        DeclarationWithType * field = strict_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                        }
377                        // do not carry over field's attributes to parameter type
378                        Type * paramType = field->get_type()->clone();
379                        deleteAll( paramType->attributes );
380                        paramType->attributes.clear();
381                        // add a parameter corresponding to this field
382                        memCtorType->parameters.push_back( new ObjectDecl( field->name, Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType, nullptr ) );
383                        FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
384                        makeFieldCtorBody( aggregateDecl->members.begin(), aggregateDecl->members.end(), ctor );
385                        resolve( ctor );
386                }
387                delete memCtorType;
388        }
389
390        void StructFuncGenerator::makeMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, bool forward ) {
391                InitTweak::InitExpander srcParam( src );
392
393                // assign to destination
394                Expression *dstselect = new MemberExpr( field, new CastExpr( new VariableExpr( dstParam ), strict_dynamic_cast< ReferenceType* >( dstParam->get_type() )->base->clone() ) );
395                genImplicitCall( srcParam, dstselect, func->name, back_inserter( func->statements->kids ), field, forward );
396        }
397
398        template<typename Iterator>
399        void StructFuncGenerator::makeFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward ) {
400                for ( ; member != end; ++member ) {
401                        if ( DeclarationWithType *field = dynamic_cast< DeclarationWithType * >( *member ) ) { // otherwise some form of type declaration, e.g. Aggregate
402                                // query the type qualifiers of this field and skip assigning it if it is marked const.
403                                // If it is an array type, we need to strip off the array layers to find its qualifiers.
404                                Type * type = field->get_type();
405                                while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
406                                        type = at->get_base();
407                                }
408
409                                if ( type->get_const() && CodeGen::isAssignment( func->name ) ) {
410                                        // don't assign const members, but do construct/destruct
411                                        continue;
412                                }
413
414                                assert( ! func->get_functionType()->get_parameters().empty() );
415                                ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().front() );
416                                ObjectDecl * srcParam = nullptr;
417                                if ( func->get_functionType()->get_parameters().size() == 2 ) {
418                                        srcParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().back() );
419                                }
420
421                                // srcParam may be NULL, in which case we have default ctor/dtor
422                                assert( dstParam );
423
424                                Expression *srcselect = srcParam ? new MemberExpr( field, new VariableExpr( srcParam ) ) : nullptr;
425                                makeMemberOp( dstParam, srcselect, field, func, forward );
426                        } // if
427                } // for
428        } // makeFunctionBody
429
430        template<typename Iterator>
431        void StructFuncGenerator::makeFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func ) {
432                FunctionType * ftype = func->type;
433                std::list<DeclarationWithType*> & params = ftype->parameters;
434                assert( params.size() >= 2 );  // should not call this function for default ctor, etc.
435
436                // skip 'this' parameter
437                ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( params.front() );
438                assert( dstParam );
439                std::list<DeclarationWithType*>::iterator parameter = params.begin()+1;
440                for ( ; member != end; ++member ) {
441                        if ( DeclarationWithType * field = dynamic_cast<DeclarationWithType*>( *member ) ) {
442                                if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
443                                        // don't make a function whose parameter is an unnamed bitfield
444                                        continue;
445                                } else if ( parameter != params.end() ) {
446                                        // matching parameter, initialize field with copy ctor
447                                        Expression *srcselect = new VariableExpr(*parameter);
448                                        makeMemberOp( dstParam, srcselect, field, func );
449                                        ++parameter;
450                                } else {
451                                        // no matching parameter, initialize field with default ctor
452                                        makeMemberOp( dstParam, nullptr, field, func );
453                                }
454                        }
455                }
456        }
457
458        bool UnionFuncGenerator::shouldAutogen() const {
459                // Builtins do not use autogeneration.
460                return ! aggregateDecl->linkage.is_builtin;
461        }
462
463        // xxx - is this right?
464        bool UnionFuncGenerator::isConcurrentType() const { return false; };
465
466        /// generate a single union assignment expression (using memcpy)
467        template< typename OutputIterator >
468        void UnionFuncGenerator::makeMemberOp( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out ) {
469                UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
470                copy->args.push_back( new AddressExpr( new VariableExpr( dstParam ) ) );
471                copy->args.push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
472                copy->args.push_back( new SizeofExpr( srcParam->get_type()->clone() ) );
473                *out++ = new ExprStmt( noLabels, copy );
474        }
475
476        /// generates the body of a union assignment/copy constructor/field constructor
477        void UnionFuncGenerator::genFuncBody( FunctionDecl * funcDecl ) {
478                FunctionType * ftype = funcDecl->type;
479                if ( InitTweak::isCopyConstructor( funcDecl ) || InitTweak::isAssignment( funcDecl ) ) {
480                        assert( ftype->parameters.size() == 2 );
481                        ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
482                        ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.back() );
483                        makeMemberOp( srcParam, dstParam, back_inserter( funcDecl->statements->kids ) );
484                } else {
485                        // default ctor/dtor body is empty - add unused attribute to parameter to silence warnings
486                        assert( ftype->parameters.size() == 1 );
487                        ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
488                        dstParam->attributes.push_back( new Attribute( "unused" ) );
489                }
490        }
491
492        /// generate the body of a constructor which takes parameters that match fields, e.g.
493        /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
494        void UnionFuncGenerator::genFieldCtors() {
495                // field ctors are only generated if default constructor and copy constructor are both generated
496                unsigned numCtors = std::count_if( definitions.begin(), definitions.end(), [](Declaration * dcl) { return CodeGen::isConstructor( dcl->get_name() ); } );
497
498                // Field constructors are only generated if default and copy constructor
499                // are generated, since they need access to both
500                if ( numCtors != 2 ) return;
501
502                // create a constructor which takes the first member type as a parameter.
503                // for example, for Union A { int x; double y; }; generate
504                // void ?{}(A *, int)
505                // This is to mimic C's behaviour which initializes the first member of the union.
506                FunctionType * memCtorType = genDefaultType( type );
507                for ( Declaration * member : aggregateDecl->members ) {
508                        DeclarationWithType * field = strict_dynamic_cast<DeclarationWithType *>( member );
509                        if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
510                                // don't make a function whose parameter is an unnamed bitfield
511                                break;
512                        }
513                        // do not carry over field's attributes to parameter type
514                        Type * paramType = field->get_type()->clone();
515                        deleteAll( paramType->attributes );
516                        paramType->attributes.clear();
517                        // add a parameter corresponding to this field
518                        memCtorType->parameters.push_back( new ObjectDecl( field->name, Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType, nullptr ) );
519                        FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
520                        ObjectDecl * srcParam = strict_dynamic_cast<ObjectDecl *>( ctor->type->parameters.back() );
521                        srcParam->fixUniqueId();
522                        ObjectDecl * dstParam = InitTweak::getParamThis( ctor->type );
523                        makeMemberOp( srcParam, dstParam, back_inserter( ctor->statements->kids ) );
524                        resolve( ctor );
525                        // only generate one field ctor for unions
526                        break;
527                }
528                delete memCtorType;
529        }
530
531        void EnumFuncGenerator::genFuncBody( FunctionDecl * funcDecl ) {
532                // xxx - Temporary: make these functions intrinsic so they codegen as C assignment.
533                // Really they're something of a cross between instrinsic and autogen, so should
534                // probably make a new linkage type
535                funcDecl->linkage = LinkageSpec::Intrinsic;
536                FunctionType * ftype = funcDecl->type;
537                if ( InitTweak::isCopyConstructor( funcDecl ) || InitTweak::isAssignment( funcDecl ) ) {
538                        assert( ftype->parameters.size() == 2 );
539                        ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
540                        ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.back() );
541
542                        // enum copy construct and assignment is just C-style assignment.
543                        // this looks like a bad recursive call, but code gen will turn it into
544                        // a C-style assignment.
545                        // This happens before function pointer type conversion, so need to do it manually here
546                        ApplicationExpr * callExpr = new ApplicationExpr( VariableExpr::functionPointer( funcDecl ) );
547                        callExpr->get_args().push_back( new VariableExpr( dstParam ) );
548                        callExpr->get_args().push_back( new VariableExpr( srcParam ) );
549                        funcDecl->statements->push_back( new ExprStmt( noLabels, callExpr ) );
550                } else {
551                        // default ctor/dtor body is empty - add unused attribute to parameter to silence warnings
552                        assert( ftype->parameters.size() == 1 );
553                        ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
554                        dstParam->attributes.push_back( new Attribute( "unused" ) );
555                }
556        }
557
558        bool EnumFuncGenerator::shouldAutogen() const { return true; }
559        bool EnumFuncGenerator::isConcurrentType() const { return false; }
560        // enums do not have field constructors
561        void EnumFuncGenerator::genFieldCtors() {}
562
563        bool TypeFuncGenerator::shouldAutogen() const { return true; };
564
565        void TypeFuncGenerator::genFuncBody( FunctionDecl * dcl ) {
566                FunctionType * ftype = dcl->type;
567                assertf( ftype->parameters.size() == 1 || ftype->parameters.size() == 2, "Incorrect number of parameters in autogenerated typedecl function: %zd", ftype->parameters.size() );
568                DeclarationWithType * dst = ftype->parameters.front();
569                DeclarationWithType * src = ftype->parameters.size() == 2 ? ftype->parameters.back() : nullptr;
570                // generate appropriate calls to member ctor, assignment
571                UntypedExpr * expr = new UntypedExpr( new NameExpr( dcl->name ) );
572                expr->args.push_back( new CastExpr( new VariableExpr( dst ), new ReferenceType( Type::Qualifiers(), typeDecl->base->clone() ) ) );
573                if ( src ) expr->args.push_back( new CastExpr( new VariableExpr( src ), typeDecl->base->clone() ) );
574                dcl->statements->kids.push_back( new ExprStmt( noLabels, expr ) );
575        };
576
577        // xxx - should reach in and determine if base type is concurrent?
578        bool TypeFuncGenerator::isConcurrentType() const { return false; };
579
580        // opaque types do not have field constructors
581        void TypeFuncGenerator::genFieldCtors() {};
582
583        //=============================================================================================
584        // Visitor definitions
585        //=============================================================================================
586        AutogenerateRoutines::AutogenerateRoutines() {
587                // the order here determines the order that these functions are generated.
588                // assignment should come last since it uses copy constructor in return.
589                data.emplace_back( "?{}", genDefaultType );
590                data.emplace_back( "?{}", genCopyType );
591                data.emplace_back( "^?{}", genDefaultType );
592                data.emplace_back( "?=?", genAssignType );
593        }
594
595        void AutogenerateRoutines::previsit( EnumDecl * enumDecl ) {
596                // must visit children (enum constants) to add them to the indexer
597                if ( enumDecl->has_body() ) {
598                        EnumInstType enumInst( Type::Qualifiers(), enumDecl->get_name() );
599                        enumInst.set_baseEnum( enumDecl );
600                        EnumFuncGenerator gen( &enumInst, data, functionNesting, indexer );
601                        generateFunctions( gen, declsToAddAfter );
602                }
603        }
604
605        void AutogenerateRoutines::previsit( StructDecl * structDecl ) {
606                visit_children = false;
607                if ( structDecl->has_body() ) {
608                        StructInstType structInst( Type::Qualifiers(), structDecl->name );
609                        structInst.set_baseStruct( structDecl );
610                        for ( TypeDecl * typeDecl : structDecl->parameters ) {
611                                structInst.parameters.push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->name, typeDecl ) ) );
612                        }
613                        StructFuncGenerator gen( structDecl, &structInst, data, functionNesting, indexer );
614                        generateFunctions( gen, declsToAddAfter );
615                } // if
616        }
617
618        void AutogenerateRoutines::previsit( UnionDecl * unionDecl ) {
619                visit_children = false;
620                if ( unionDecl->has_body()  ) {
621                        UnionInstType unionInst( Type::Qualifiers(), unionDecl->get_name() );
622                        unionInst.set_baseUnion( unionDecl );
623                        for ( TypeDecl * typeDecl : unionDecl->get_parameters() ) {
624                                unionInst.get_parameters().push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), typeDecl ) ) );
625                        }
626                        UnionFuncGenerator gen( unionDecl, &unionInst, data, functionNesting, indexer );
627                        generateFunctions( gen, declsToAddAfter );
628                } // if
629        }
630
631        // generate ctor/dtors/assign for typedecls, e.g., otype T = int *;
632        void AutogenerateRoutines::previsit( TypeDecl * typeDecl ) {
633                if ( ! typeDecl->base ) return;
634
635                TypeInstType refType( Type::Qualifiers(), typeDecl->name, typeDecl );
636                TypeFuncGenerator gen( typeDecl, &refType, data, functionNesting, indexer );
637                generateFunctions( gen, declsToAddAfter );
638
639        }
640
641        void AutogenerateRoutines::previsit( TraitDecl * ) {
642                // ensure that we don't add assignment ops for types defined as part of the trait
643                visit_children = false;
644        }
645
646        void AutogenerateRoutines::previsit( FunctionDecl * ) {
647                // Track whether we're currently in a function.
648                // Can ignore function type idiosyncrasies, because function type can never
649                // declare a new type.
650                functionNesting += 1;
651                GuardAction( [this]()  { functionNesting -= 1; } );
652        }
653
654        void AutogenerateRoutines::previsit( CompoundStmt * ) {
655                GuardScope( structsDone );
656        }
657
658        void makeTupleFunctionBody( FunctionDecl * function ) {
659                FunctionType * ftype = function->get_functionType();
660                assertf( ftype->get_parameters().size() == 1 || ftype->get_parameters().size() == 2, "too many parameters in generated tuple function" );
661
662                UntypedExpr * untyped = new UntypedExpr( new NameExpr( function->get_name() ) );
663
664                /// xxx - &* is used to make this easier for later passes to handle
665                untyped->get_args().push_back( new AddressExpr( UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
666                if ( ftype->get_parameters().size() == 2 ) {
667                        untyped->get_args().push_back( new VariableExpr( ftype->get_parameters().back() ) );
668                }
669                function->get_statements()->get_kids().push_back( new ExprStmt( noLabels, untyped ) );
670                function->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
671        }
672
673        void AutogenTupleRoutines::postvisit( TupleType * tupleType ) {
674                std::string mangleName = SymTab::Mangler::mangleType( tupleType );
675                if ( seenTuples.find( mangleName ) != seenTuples.end() ) return;
676                seenTuples.insert( mangleName );
677
678                // T ?=?(T *, T);
679                FunctionType *assignType = genAssignType( tupleType );
680
681                // void ?{}(T *); void ^?{}(T *);
682                FunctionType *ctorType = genDefaultType( tupleType );
683                FunctionType *dtorType = genDefaultType( tupleType );
684
685                // void ?{}(T *, T);
686                FunctionType *copyCtorType = genCopyType( tupleType );
687
688                std::set< TypeDecl* > done;
689                std::list< TypeDecl * > typeParams;
690                for ( Type * t : *tupleType ) {
691                        if ( TypeInstType * ty = dynamic_cast< TypeInstType * >( t ) ) {
692                                if ( ! done.count( ty->get_baseType() ) ) {
693                                        TypeDecl * newDecl = new TypeDecl( ty->get_baseType()->get_name(), Type::StorageClasses(), nullptr, TypeDecl::Dtype, true );
694                                        TypeInstType * inst = new TypeInstType( Type::Qualifiers(), newDecl->get_name(), newDecl );
695                                        newDecl->get_assertions().push_back( new FunctionDecl( "?=?", Type::StorageClasses(), LinkageSpec::Cforall, genAssignType( inst ), nullptr,
696                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
697                                        newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
698                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
699                                        newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genCopyType( inst ), nullptr,
700                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
701                                        newDecl->get_assertions().push_back( new FunctionDecl( "^?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
702                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
703                                        typeParams.push_back( newDecl );
704                                        done.insert( ty->get_baseType() );
705                                }
706                        }
707                }
708                cloneAll( typeParams, ctorType->get_forall() );
709                cloneAll( typeParams, dtorType->get_forall() );
710                cloneAll( typeParams, copyCtorType->get_forall() );
711                cloneAll( typeParams, assignType->get_forall() );
712
713                FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting );
714                FunctionDecl *ctorDecl = genFunc( "?{}", ctorType, functionNesting );
715                FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting );
716                FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting );
717
718                makeTupleFunctionBody( assignDecl );
719                makeTupleFunctionBody( ctorDecl );
720                makeTupleFunctionBody( copyCtorDecl );
721                makeTupleFunctionBody( dtorDecl );
722
723                declsToAddBefore.push_back( ctorDecl );
724                declsToAddBefore.push_back( copyCtorDecl );
725                declsToAddBefore.push_back( dtorDecl );
726                declsToAddBefore.push_back( assignDecl ); // assignment should come last since it uses copy constructor in return
727        }
728
729        void AutogenTupleRoutines::previsit( FunctionDecl *functionDecl ) {
730                visit_children = false;
731                maybeAccept( functionDecl->type, *visitor );
732                functionNesting += 1;
733                maybeAccept( functionDecl->statements, *visitor );
734                functionNesting -= 1;
735        }
736
737        void AutogenTupleRoutines::previsit( CompoundStmt * ) {
738                GuardScope( seenTuples );
739        }
740} // SymTab
741
742// Local Variables: //
743// tab-width: 4 //
744// mode: c++ //
745// compile-command: "make install" //
746// End: //
Note: See TracBrowser for help on using the repository browser.