source: src/SymTab/Autogen.cc @ 69c5c00

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 69c5c00 was 31a5caba, checked in by Fangren Yu <f37yu@…>, 4 years ago

generate deleted declaration for invalid autogens

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