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
RevLine 
[972e6f7]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
[6926a6d]11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Apr 27 14:39:06 2018
13// Update Count     : 63
[972e6f7]14//
15
16#include "Autogen.h"
[30f9072]17
18#include <algorithm>               // for count_if
[e3e16bc]19#include <cassert>                 // for strict_dynamic_cast, assert, assertf
[30f9072]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
[be9288a]23#include <utility>                 // for pair
[30f9072]24#include <vector>                  // for vector
25
[b8524ca]26#include "AST/Decl.hpp"
[9236060]27#include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
[e4d6335]28#include "Common/PassVisitor.h"    // for PassVisitor
[30f9072]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
[8b11840]32#include "InitTweak/GenInit.h"     // for fixReturnStatements
33#include "ResolvExpr/Resolver.h"   // for resolveDecl
[30f9072]34#include "SymTab/Mangler.h"        // for Mangler
[9236060]35#include "SynTree/Attribute.h"     // For Attribute
[30f9072]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;
[972e6f7]42
43namespace SymTab {
[a117f7c]44        /// Data used to generate functions generically. Specifically, the name of the generated function and a function which generates the routine protoype
[207c7e1d]45        struct FuncData {
[837ce06]46                typedef FunctionType * (*TypeGen)( Type *, bool );
[a117f7c]47                FuncData( const std::string & fname, const TypeGen & genType ) : fname( fname ), genType( genType ) {}
[207c7e1d]48                std::string fname;
49                TypeGen genType;
50        };
[5f98ce5]51
[189d800]52        struct AutogenerateRoutines final : public WithDeclsToAdd, public WithVisitorRef<AutogenerateRoutines>, public WithGuards, public WithShortCircuiting, public WithIndexer {
[207c7e1d]53                AutogenerateRoutines();
54
[e4d6335]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 );
[972e6f7]61
[e4d6335]62                void previsit( CompoundStmt * compoundStmt );
[972e6f7]63
[1486116]64          private:
[a117f7c]65
[e4d6335]66                GenPoly::ScopedSet< std::string > structsDone;
[1486116]67                unsigned int functionNesting = 0;     // current level of nested functions
[a117f7c]68
[207c7e1d]69                std::vector< FuncData > data;
[1486116]70        };
71
72        /// generates routines for tuple types.
[ac74057]73        struct AutogenTupleRoutines : public WithDeclsToAdd, public WithVisitorRef<AutogenTupleRoutines>, public WithGuards, public WithShortCircuiting {
[a117f7c]74                void previsit( FunctionDecl * functionDecl );
[1486116]75
[a117f7c]76                void postvisit( TupleType * tupleType );
[1486116]77
[a117f7c]78                void previsit( CompoundStmt * compoundStmt );
[1486116]79
80          private:
81                unsigned int functionNesting = 0;     // current level of nested functions
82                GenPoly::ScopedSet< std::string > seenTuples;
[972e6f7]83        };
84
85        void autogenerateRoutines( std::list< Declaration * > &translationUnit ) {
[e4d6335]86                PassVisitor<AutogenerateRoutines> generator;
87                acceptAll( translationUnit, generator );
[1486116]88
89                // needs to be done separately because AutogenerateRoutines skips types that appear as function arguments, etc.
90                // AutogenTupleRoutines tupleGenerator;
[ac74057]91                // acceptAll( translationUnit, tupleGenerator );
[972e6f7]92        }
93
[a117f7c]94        //=============================================================================================
95        // FuncGenerator definitions
96        //=============================================================================================
97        class FuncGenerator {
98        public:
99                std::list< Declaration * > definitions, forwards;
100
[0a267c1]101                FuncGenerator( Type * type, const std::vector< FuncData > & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : type( type ), data( data ), functionNesting( functionNesting ), indexer( indexer ) {}
[a117f7c]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;
[0a267c1]109                unsigned int functionNesting;
[a117f7c]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:
[0a267c1]122                StructFuncGenerator( StructDecl * aggregateDecl, StructInstType * refType, const std::vector< FuncData > & data,  unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), aggregateDecl( aggregateDecl) {}
[a117f7c]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
[0a267c1]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
[18ca28e]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
[a117f7c]183        class TypeFuncGenerator : public FuncGenerator {
184                TypeDecl * typeDecl;
185        public:
[0a267c1]186                TypeFuncGenerator( TypeDecl * typeDecl, TypeInstType * refType, const std::vector<FuncData> & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), typeDecl( typeDecl ) {}
[a117f7c]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
[356189a]208        bool isUnnamedBitfield( ObjectDecl * obj ) {
[f30b2610]209                return obj != nullptr && obj->name == "" && obj->bitfieldWidth != nullptr;
[356189a]210        }
211
[b8524ca]212        bool isUnnamedBitfield( const ast::ObjectDecl * obj ) {
213                return obj && obj->name.empty() && obj->bitfieldWidth;
214        }
215
[186fd86]216        /// inserts a forward declaration for functionDecl into declsToAdd
217        void addForwardDecl( FunctionDecl * functionDecl, std::list< Declaration * > & declsToAdd ) {
218                FunctionDecl * decl = functionDecl->clone();
[f30b2610]219                delete decl->statements;
220                decl->statements = nullptr;
[186fd86]221                declsToAdd.push_back( decl );
222                decl->fixUniqueId();
[972e6f7]223        }
224
[f30b2610]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
[186fd86]235        /// given type T, generate type of default ctor/dtor, i.e. function type void (*) (T *)
[837ce06]236        FunctionType * genDefaultType( Type * paramType, bool maybePolymorphic ) {
[186fd86]237                FunctionType *ftype = new FunctionType( Type::Qualifiers(), false );
[837ce06]238                if ( maybePolymorphic ) {
239                        // only copy in
240                        const auto & typeParams = getGenericParams( paramType );
241                        cloneAll( typeParams, ftype->forall );
242                }
[49148d5]243                ObjectDecl *dstParam = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new ReferenceType( Type::Qualifiers(), paramType->clone() ), nullptr );
[f30b2610]244                ftype->parameters.push_back( dstParam );
[186fd86]245                return ftype;
246        }
[d0f8b19]247
[186fd86]248        /// given type T, generate type of copy ctor, i.e. function type void (*) (T *, T)
[837ce06]249        FunctionType * genCopyType( Type * paramType, bool maybePolymorphic ) {
250                FunctionType *ftype = genDefaultType( paramType, maybePolymorphic );
[68fe077a]251                ObjectDecl *srcParam = new ObjectDecl( "_src", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
[f30b2610]252                ftype->parameters.push_back( srcParam );
[186fd86]253                return ftype;
254        }
[d0f8b19]255
[186fd86]256        /// given type T, generate type of assignment, i.e. function type T (*) (T *, T)
[837ce06]257        FunctionType * genAssignType( Type * paramType, bool maybePolymorphic ) {
258                FunctionType *ftype = genCopyType( paramType, maybePolymorphic );
[68fe077a]259                ObjectDecl *returnVal = new ObjectDecl( "_ret", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
[f30b2610]260                ftype->returnVals.push_back( returnVal );
[186fd86]261                return ftype;
262        }
[972e6f7]263
[186fd86]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
[972e6f7]268                // because each unit generates copies of the default routines for each aggregate.
[68fe077a]269                Type::StorageClasses scs = functionNesting > 0 ? Type::StorageClasses() : Type::StorageClasses( Type::Static );
[186fd86]270                LinkageSpec::Spec spec = isIntrinsic ? LinkageSpec::Intrinsic : LinkageSpec::AutoGen;
[ba3706f]271                FunctionDecl * decl = new FunctionDecl( fname, scs, spec, ftype, new CompoundStmt(),
[ddfd945]272                                                                                                std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) );
[186fd86]273                decl->fixUniqueId();
274                return decl;
275        }
[d0f8b19]276
[a117f7c]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 );
[f232977]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() );
[ba3706f]306                                dcl->statements->push_back( new ReturnStmt( new VariableExpr( dstParam ) ) );
[f232977]307                        }
[a117f7c]308                        resolve( dcl );
309                }
310        }
311
312        void FuncGenerator::generatePrototypes( std::list< FunctionDecl * > & newFuncs ) {
313                bool concurrent_type = isConcurrentType();
[e220391]314                for ( const FuncData & d : data ) {
[a117f7c]315                        // generate a function (?{}, ?=?, ^?{}) based on the current FuncData.
[4ee1efb]316                        FunctionType * ftype = d.genType( type, true );
[a117f7c]317
318                        // destructor for concurrent type must be mutex
[e220391]319                        if ( concurrent_type && CodeGen::isDestructor( d.fname ) ) {
[a117f7c]320                                ftype->parameters.front()->get_type()->set_mutex( true );
321                        }
322
[e220391]323                        newFuncs.push_back( genFunc( d.fname, ftype, functionNesting ) );
[a117f7c]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 );
[6926a6d]339                } catch ( SemanticErrorException & ) {
[a117f7c]340                        // okay if decl does not resolve - that means the function should not be generated
[31a5caba]341                        // delete dcl;
342                        delete dcl->statements;
343                        dcl->statements = nullptr;
344                        dcl->isDeleted = true;
345                        definitions.push_back( dcl );
346                        indexer.addId( dcl );
[a117f7c]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
[f30b2610]359                if ( ! CodeGen::isDestructor( dcl->name ) ) {
[a117f7c]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
[f30b2610]368                unsigned numCtors = std::count_if( definitions.begin(), definitions.end(), [](Declaration * dcl) { return CodeGen::isConstructor( dcl->name ); } );
[a117f7c]369
[0a267c1]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
[a117f7c]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)
[0a267c1]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;
[a117f7c]383                        }
[1f370451]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
[54c9000]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 );
[0a267c1]392                        FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
393                        makeFieldCtorBody( aggregateDecl->members.begin(), aggregateDecl->members.end(), ctor );
394                        resolve( ctor );
[a117f7c]395                }
[0a267c1]396                delete memCtorType;
[a117f7c]397        }
398
399        void StructFuncGenerator::makeMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, bool forward ) {
[b8524ca]400                InitTweak::InitExpander_old srcParam( src );
[39f84a4]401
[49148d5]402                // assign to destination
[f30b2610]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 );
[dac0aa9]405        }
406
[972e6f7]407        template<typename Iterator>
[a117f7c]408        void StructFuncGenerator::makeFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward ) {
[972e6f7]409                for ( ; member != end; ++member ) {
[dac0aa9]410                        if ( DeclarationWithType *field = dynamic_cast< DeclarationWithType * >( *member ) ) { // otherwise some form of type declaration, e.g. Aggregate
[972e6f7]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.
[dac0aa9]413                                Type * type = field->get_type();
[972e6f7]414                                while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
415                                        type = at->get_base();
416                                }
417
[6fc5c14]418                                if ( type->get_const() && CodeGen::isAssignment( func->name ) ) {
[cad355a]419                                        // don't assign const members, but do construct/destruct
[972e6f7]420                                        continue;
421                                }
422
423                                assert( ! func->get_functionType()->get_parameters().empty() );
424                                ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().front() );
[8b11840]425                                ObjectDecl * srcParam = nullptr;
[972e6f7]426                                if ( func->get_functionType()->get_parameters().size() == 2 ) {
427                                        srcParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().back() );
428                                }
[1a5ad8c]429
[972e6f7]430                                // srcParam may be NULL, in which case we have default ctor/dtor
431                                assert( dstParam );
432
[8b11840]433                                Expression *srcselect = srcParam ? new MemberExpr( field, new VariableExpr( srcParam ) ) : nullptr;
[a117f7c]434                                makeMemberOp( dstParam, srcselect, field, func, forward );
[972e6f7]435                        } // if
436                } // for
[a117f7c]437        } // makeFunctionBody
[972e6f7]438
[dac0aa9]439        template<typename Iterator>
[a117f7c]440        void StructFuncGenerator::makeFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func ) {
441                FunctionType * ftype = func->type;
442                std::list<DeclarationWithType*> & params = ftype->parameters;
[dac0aa9]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 ) ) {
[0b4d93ab]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() ) {
[dac0aa9]455                                        // matching parameter, initialize field with copy ctor
456                                        Expression *srcselect = new VariableExpr(*parameter);
[a117f7c]457                                        makeMemberOp( dstParam, srcselect, field, func );
[dac0aa9]458                                        ++parameter;
459                                } else {
460                                        // no matching parameter, initialize field with default ctor
[a117f7c]461                                        makeMemberOp( dstParam, nullptr, field, func );
[189d800]462                                }
[356189a]463                        }
[dac0aa9]464                }
[972e6f7]465        }
466
[0a267c1]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
[186fd86]475        /// generate a single union assignment expression (using memcpy)
476        template< typename OutputIterator >
[0a267c1]477        void UnionFuncGenerator::makeMemberOp( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out ) {
[186fd86]478                UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
[0a267c1]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() ) );
[ba3706f]482                *out++ = new ExprStmt( copy );
[186fd86]483        }
[972e6f7]484
[186fd86]485        /// generates the body of a union assignment/copy constructor/field constructor
[0a267c1]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" ) );
[186fd86]498                }
499        }
[972e6f7]500
[0a267c1]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() ); } );
[972e6f7]506
[0a267c1]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;
[972e6f7]510
[a465caf]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.
[0a267c1]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
[a465caf]520                                break;
521                        }
[1f370451]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 ) );
[0a267c1]528                        FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
529                        ObjectDecl * srcParam = strict_dynamic_cast<ObjectDecl *>( ctor->type->parameters.back() );
[582ee28]530                        srcParam->fixUniqueId();
[0a267c1]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;
[a465caf]536                }
[0a267c1]537                delete memCtorType;
[972e6f7]538        }
539
[18ca28e]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 ) );
[ba3706f]558                        funcDecl->statements->push_back( new ExprStmt( callExpr ) );
[18ca28e]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
[a117f7c]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() ) );
[ba3706f]583                dcl->statements->kids.push_back( new ExprStmt( expr ) );
[a117f7c]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
[18ca28e]590        void TypeFuncGenerator::genFieldCtors() {};
[a117f7c]591
592        //=============================================================================================
593        // Visitor definitions
594        //=============================================================================================
[207c7e1d]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.
[a117f7c]598                data.emplace_back( "?{}", genDefaultType );
599                data.emplace_back( "?{}", genCopyType );
600                data.emplace_back( "^?{}", genDefaultType );
601                data.emplace_back( "?=?", genAssignType );
[207c7e1d]602        }
603
[8b11840]604        void AutogenerateRoutines::previsit( EnumDecl * enumDecl ) {
[189d800]605                // must visit children (enum constants) to add them to the indexer
606                if ( enumDecl->has_body() ) {
[18ca28e]607                        EnumInstType enumInst( Type::Qualifiers(), enumDecl->get_name() );
608                        enumInst.set_baseEnum( enumDecl );
609                        EnumFuncGenerator gen( &enumInst, data, functionNesting, indexer );
610                        generateFunctions( gen, declsToAddAfter );
[972e6f7]611                }
612        }
613
[8b11840]614        void AutogenerateRoutines::previsit( StructDecl * structDecl ) {
[e4d6335]615                visit_children = false;
[a117f7c]616                if ( structDecl->has_body() ) {
[8b11840]617                        StructInstType structInst( Type::Qualifiers(), structDecl->name );
[a117f7c]618                        structInst.set_baseStruct( structDecl );
[8b11840]619                        for ( TypeDecl * typeDecl : structDecl->parameters ) {
620                                structInst.parameters.push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->name, typeDecl ) ) );
[186fd86]621                        }
[a117f7c]622                        StructFuncGenerator gen( structDecl, &structInst, data, functionNesting, indexer );
623                        generateFunctions( gen, declsToAddAfter );
[972e6f7]624                } // if
625        }
626
[8b11840]627        void AutogenerateRoutines::previsit( UnionDecl * unionDecl ) {
[e4d6335]628                visit_children = false;
[a117f7c]629                if ( unionDecl->has_body()  ) {
[972e6f7]630                        UnionInstType unionInst( Type::Qualifiers(), unionDecl->get_name() );
631                        unionInst.set_baseUnion( unionDecl );
[186fd86]632                        for ( TypeDecl * typeDecl : unionDecl->get_parameters() ) {
633                                unionInst.get_parameters().push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), typeDecl ) ) );
634                        }
[0a267c1]635                        UnionFuncGenerator gen( unionDecl, &unionInst, data, functionNesting, indexer );
636                        generateFunctions( gen, declsToAddAfter );
[972e6f7]637                } // if
638        }
639
[108f3cdb]640        // generate ctor/dtors/assign for typedecls, e.g., otype T = int *;
[8b11840]641        void AutogenerateRoutines::previsit( TypeDecl * typeDecl ) {
[108f3cdb]642                if ( ! typeDecl->base ) return;
643
644                TypeInstType refType( Type::Qualifiers(), typeDecl->name, typeDecl );
[0a267c1]645                TypeFuncGenerator gen( typeDecl, &refType, data, functionNesting, indexer );
[a117f7c]646                generateFunctions( gen, declsToAddAfter );
[972e6f7]647
648        }
649
[e4d6335]650        void AutogenerateRoutines::previsit( TraitDecl * ) {
[a5a71d0]651                // ensure that we don't add assignment ops for types defined as part of the trait
[e4d6335]652                visit_children = false;
[972e6f7]653        }
654
[f203a7a]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.
[972e6f7]659                functionNesting += 1;
[f203a7a]660                GuardAction( [this]()  { functionNesting -= 1; } );
[972e6f7]661        }
662
[e4d6335]663        void AutogenerateRoutines::previsit( CompoundStmt * ) {
664                GuardScope( structsDone );
[972e6f7]665        }
[1486116]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                }
[ba3706f]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() ) ) ) );
[1486116]680        }
681
[ac74057]682        void AutogenTupleRoutines::postvisit( TupleType * tupleType ) {
[1486116]683                std::string mangleName = SymTab::Mangler::mangleType( tupleType );
[ac74057]684                if ( seenTuples.find( mangleName ) != seenTuples.end() ) return;
[1486116]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() ) ) {
[f0ecf9b]702                                        TypeDecl * newDecl = new TypeDecl( ty->get_baseType()->get_name(), Type::StorageClasses(), nullptr, TypeDecl::Dtype, true );
[1486116]703                                        TypeInstType * inst = new TypeInstType( Type::Qualifiers(), newDecl->get_name(), newDecl );
[68fe077a]704                                        newDecl->get_assertions().push_back( new FunctionDecl( "?=?", Type::StorageClasses(), LinkageSpec::Cforall, genAssignType( inst ), nullptr,
[ddfd945]705                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
[68fe077a]706                                        newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
[ddfd945]707                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
[68fe077a]708                                        newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genCopyType( inst ), nullptr,
[ddfd945]709                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
[68fe077a]710                                        newDecl->get_assertions().push_back( new FunctionDecl( "^?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
[ddfd945]711                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
[1486116]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
[ac74057]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
[1486116]736        }
737
[ac74057]738        void AutogenTupleRoutines::previsit( FunctionDecl *functionDecl ) {
739                visit_children = false;
[a139c11]740                maybeAccept( functionDecl->type, *visitor );
[1486116]741                functionNesting += 1;
[a139c11]742                maybeAccept( functionDecl->statements, *visitor );
[1486116]743                functionNesting -= 1;
744        }
745
[ac74057]746        void AutogenTupleRoutines::previsit( CompoundStmt * ) {
747                GuardScope( seenTuples );
[1486116]748        }
[972e6f7]749} // SymTab
[c0aa336]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.