source: src/Validate/Autogen.cpp @ 24d6572

ast-experimental
Last change on this file since 24d6572 was 24d6572, checked in by Fangren Yu <f37yu@…>, 13 months ago

Merge branch 'master' into ast-experimental

  • Property mode set to 100644
File size: 28.3 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.cpp -- Generate automatic routines for data types.
8//
9// Author           : Andrew Beach
10// Created On       : Thu Dec  2 13:44:00 2021
11// Last Modified By : Andrew Beach
12// Last Modified On : Tue Sep 20 16:00:00 2022
13// Update Count     : 2
14//
15
16#include "Autogen.hpp"
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/Attribute.hpp"
27#include "AST/Copy.hpp"
28#include "AST/Create.hpp"
29#include "AST/Decl.hpp"
30#include "AST/DeclReplacer.hpp"
31#include "AST/Expr.hpp"
32#include "AST/Inspect.hpp"
33#include "AST/Pass.hpp"
34#include "AST/Stmt.hpp"
35#include "AST/SymbolTable.hpp"
36#include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
37#include "Common/ScopedMap.h"      // for ScopedMap<>::const_iterator, Scope...
38#include "Common/utility.h"        // for cloneAll, operator+
39#include "GenPoly/ScopedSet.h"     // for ScopedSet, ScopedSet<>::iterator
40#include "InitTweak/GenInit.h"     // for fixReturnStatements
41#include "InitTweak/InitTweak.h"   // for isAssignment, isCopyConstructor
42#include "SymTab/GenImplicitCall.hpp"  // for genImplicitCall
43#include "SymTab/Mangler.h"        // for Mangler
44#include "CompilationState.h"
45
46namespace Validate {
47
48namespace {
49
50// --------------------------------------------------------------------------
51struct AutogenerateRoutines_new final :
52                public ast::WithDeclsToAdd<>,
53                public ast::WithShortCircuiting {
54        void previsit( const ast::EnumDecl * enumDecl );
55        void previsit( const ast::StructDecl * structDecl );
56        void previsit( const ast::UnionDecl * structDecl );
57        void previsit( const ast::TypeDecl * typeDecl );
58        void previsit( const ast::TraitDecl * traitDecl );
59        void previsit( const ast::FunctionDecl * functionDecl );
60        void postvisit( const ast::FunctionDecl * functionDecl );
61
62private:
63        // Current level of nested functions.
64        unsigned int functionNesting = 0;
65};
66
67// --------------------------------------------------------------------------
68/// Class used to generate functions for a particular declaration.
69/// Note it isn't really stored, it is just a class for organization and to
70/// help pass around some of the common arguments.
71class FuncGenerator {
72public:
73        std::list<ast::ptr<ast::Decl>> forwards;
74        std::list<ast::ptr<ast::Decl>> definitions;
75
76        FuncGenerator( const ast::Type * type, unsigned int functionNesting ) :
77                type( type ), functionNesting( functionNesting )
78        {}
79
80        /// Generate functions (and forward decls.) and append them to the list.
81        void generateAndAppendFunctions( std::list<ast::ptr<ast::Decl>> & );
82
83        virtual bool shouldAutogen() const = 0;
84protected:
85        const ast::Type * type;
86        unsigned int functionNesting;
87        ast::Linkage::Spec proto_linkage = ast::Linkage::AutoGen;
88
89        // Internal helpers:
90        void genStandardFuncs();
91        void produceDecl( const ast::FunctionDecl * decl );
92        void produceForwardDecl( const ast::FunctionDecl * decl );
93
94        const CodeLocation& getLocation() const { return getDecl()->location; }
95        ast::FunctionDecl * genProto( std::string&& name,
96                std::vector<ast::ptr<ast::DeclWithType>>&& params,
97                std::vector<ast::ptr<ast::DeclWithType>>&& returns ) const;
98
99        ast::ObjectDecl * dstParam() const;
100        ast::ObjectDecl * srcParam() const;
101        ast::FunctionDecl * genCtorProto() const;
102        ast::FunctionDecl * genCopyProto() const;
103        ast::FunctionDecl * genDtorProto() const;
104        ast::FunctionDecl * genAssignProto() const;
105        ast::FunctionDecl * genFieldCtorProto( unsigned int fields ) const;
106
107        // Internal Hooks:
108        virtual void genFuncBody( ast::FunctionDecl * decl ) = 0;
109        virtual void genFieldCtors() = 0;
110        virtual bool isConcurrentType() const { return false; }
111        virtual const ast::Decl * getDecl() const = 0;
112};
113
114class StructFuncGenerator final : public FuncGenerator {
115        const ast::StructDecl * decl;
116public:
117        StructFuncGenerator( const ast::StructDecl * decl,
118                        const ast::StructInstType * type,
119                        unsigned int functionNesting ) :
120                FuncGenerator( type, functionNesting ), decl( decl )
121        {}
122
123        // Built-ins do not use autogeneration.
124        bool shouldAutogen() const final { return !decl->linkage.is_builtin && !structHasFlexibleArray(decl); }
125private:
126        void genFuncBody( ast::FunctionDecl * decl ) final;
127        void genFieldCtors() final;
128        bool isConcurrentType() const final {
129                return decl->is_thread() || decl->is_monitor();
130        }
131        virtual const ast::Decl * getDecl() const final { return decl; }
132
133        /// Generates a single struct member operation.
134        /// (constructor call, destructor call, assignment call)
135        // This is managed because it uses another helper that returns a ast::ptr.
136        ast::ptr<ast::Stmt> makeMemberOp(
137                const CodeLocation& location,
138                const ast::ObjectDecl * dstParam, const ast::Expr * src,
139                const ast::ObjectDecl * field, ast::FunctionDecl * func,
140                SymTab::LoopDirection direction );
141
142        /// Generates the body of a struct function by iterating the struct members
143        /// (via parameters). Generates default constructor, copy constructor,
144        /// copy assignment, and destructor bodies. No field constructor bodies.
145        template<typename Iterator>
146        void makeFunctionBody( Iterator member, Iterator end,
147                        ast::FunctionDecl * func, SymTab::LoopDirection direction );
148
149        /// Generate the body of a constructor which takes parameters that match
150        /// fields. (With arguments for one to all of the fields.)
151        template<typename Iterator>
152        void makeFieldCtorBody( Iterator member, Iterator end,
153                        ast::FunctionDecl * func );
154};
155
156class UnionFuncGenerator final : public FuncGenerator {
157        const ast::UnionDecl * decl;
158public:
159        UnionFuncGenerator( const ast::UnionDecl * decl,
160                        const ast::UnionInstType * type,
161                        unsigned int functionNesting ) :
162                FuncGenerator( type, functionNesting ), decl( decl )
163        {}
164
165        // Built-ins do not use autogeneration.
166        bool shouldAutogen() const final { return !decl->linkage.is_builtin; }
167private:
168        void genFuncBody( ast::FunctionDecl * decl ) final;
169        void genFieldCtors() final;
170        const ast::Decl * getDecl() const final { return decl; }
171
172        /// Generate a single union assignment expression (using memcpy).
173        ast::ExprStmt * makeAssignOp( const CodeLocation& location,
174                const ast::ObjectDecl * dstParam, const ast::ObjectDecl * srcParam );
175};
176
177class EnumFuncGenerator final : public FuncGenerator {
178        const ast::EnumDecl * decl;
179public:
180        EnumFuncGenerator( const ast::EnumDecl * decl,
181                        const ast::EnumInstType * type,
182                        unsigned int functionNesting ) :
183                FuncGenerator( type, functionNesting ), decl( decl )
184        {
185                // TODO: These functions are somewhere between instrinsic and autogen,
186                // could possibly use a new linkage type. For now we just make the
187                // basic ones intrinsic to code-gen them as C assignments.
188                const auto & real_type = decl->base;
189                const auto & basic = real_type.as<ast::BasicType>();
190                if(!real_type || (basic && basic->isInteger())) proto_linkage = ast::Linkage::Intrinsic;
191        }
192
193        bool shouldAutogen() const final { return true; }
194private:
195        void genFuncBody( ast::FunctionDecl * decl ) final;
196        void genFieldCtors() final;
197        const ast::Decl * getDecl() const final { return decl; }
198};
199
200class TypeFuncGenerator final : public FuncGenerator {
201        const ast::TypeDecl * decl;
202public:
203        TypeFuncGenerator( const ast::TypeDecl * decl,
204                        ast::TypeInstType * type,
205                        unsigned int functionNesting ) :
206                FuncGenerator( type, functionNesting ), decl( decl )
207        {}
208
209        bool shouldAutogen() const final { return true; }
210        void genFieldCtors() final;
211private:
212        void genFuncBody( ast::FunctionDecl * decl ) final;
213        const ast::Decl * getDecl() const final { return decl; }
214};
215
216// --------------------------------------------------------------------------
217const std::vector<ast::ptr<ast::TypeDecl>>& getGenericParams( const ast::Type * t ) {
218        if ( auto inst = dynamic_cast< const ast::StructInstType * >( t ) ) {
219                return inst->base->params;
220        } else if ( auto inst = dynamic_cast< const ast::UnionInstType * >( t ) ) {
221                return inst->base->params;
222        }
223        static std::vector<ast::ptr<ast::TypeDecl>> const empty;
224        return empty;
225}
226
227/// Changes the node inside a pointer so that it has the unused attribute.
228void addUnusedAttribute( ast::ptr<ast::DeclWithType> & declPtr ) {
229        ast::DeclWithType * decl = declPtr.get_and_mutate();
230        decl->attributes.push_back( new ast::Attribute( "unused" ) );
231}
232
233// --------------------------------------------------------------------------
234void AutogenerateRoutines_new::previsit( const ast::EnumDecl * enumDecl ) {
235        // Must visit children (enum constants) to add them to the symbol table.
236        if ( !enumDecl->body ) return;
237
238        // if ( auto enumBaseType = enumDecl->base ) {
239        //      if ( auto enumBaseTypeAsStructInst = dynamic_cast<const ast::StructInstType *>(enumBaseType.get()) ) {
240        //              const ast::StructDecl * structDecl = enumBaseTypeAsStructInst->base.get();
241        //              this->previsit( structDecl );
242        //      }
243        // }
244
245        ast::EnumInstType enumInst( enumDecl->name );
246        enumInst.base = enumDecl;
247        EnumFuncGenerator gen( enumDecl, &enumInst, functionNesting );
248        gen.generateAndAppendFunctions( declsToAddAfter );
249}
250
251void AutogenerateRoutines_new::previsit( const ast::StructDecl * structDecl ) {
252        visit_children = false;
253        if ( !structDecl->body ) return;
254
255        ast::StructInstType structInst( structDecl->name );
256        structInst.base = structDecl;
257        for ( const ast::TypeDecl * typeDecl : structDecl->params ) {
258                structInst.params.push_back( new ast::TypeExpr(
259                        typeDecl->location,
260                        new ast::TypeInstType( typeDecl )
261                ) );
262        }
263        StructFuncGenerator gen( structDecl, &structInst, functionNesting );
264        gen.generateAndAppendFunctions( declsToAddAfter );
265}
266
267void AutogenerateRoutines_new::previsit( const ast::UnionDecl * unionDecl ) {
268        visit_children = false;
269        if ( !unionDecl->body ) return;
270
271        ast::UnionInstType unionInst( unionDecl->name );
272        unionInst.base = unionDecl;
273        for ( const ast::TypeDecl * typeDecl : unionDecl->params ) {
274                unionInst.params.push_back( new ast::TypeExpr(
275                        unionDecl->location,
276                        new ast::TypeInstType( typeDecl )
277                ) );
278        }
279        UnionFuncGenerator gen( unionDecl, &unionInst, functionNesting );
280        gen.generateAndAppendFunctions( declsToAddAfter );
281}
282
283/// Generate ctor/dtors/assign for typedecls, e.g., otype T = int *;
284void AutogenerateRoutines_new::previsit( const ast::TypeDecl * typeDecl ) {
285        if ( !typeDecl->base ) return;
286
287        ast::TypeInstType refType( typeDecl->name, typeDecl );
288        TypeFuncGenerator gen( typeDecl, &refType, functionNesting );
289        gen.generateAndAppendFunctions( declsToAddAfter );
290}
291
292void AutogenerateRoutines_new::previsit( const ast::TraitDecl * ) {
293        // Ensure that we don't add assignment ops for types defined as part of the trait
294        visit_children = false;
295}
296
297void AutogenerateRoutines_new::previsit( const ast::FunctionDecl * ) {
298        // Track whether we're currently in a function.
299        // Can ignore function type idiosyncrasies, because function type can never
300        // declare a new type.
301        functionNesting += 1;
302}
303
304void AutogenerateRoutines_new::postvisit( const ast::FunctionDecl * ) {
305        functionNesting -= 1;
306}
307
308void FuncGenerator::generateAndAppendFunctions(
309                std::list<ast::ptr<ast::Decl>> & decls ) {
310        if ( !shouldAutogen() ) return;
311
312        // Generate the functions (they go into forwards and definitions).
313        genStandardFuncs();
314        genFieldCtors();
315
316        // Now export the lists contents.
317        decls.splice( decls.end(), forwards );
318        decls.splice( decls.end(), definitions );
319}
320
321void FuncGenerator::produceDecl( const ast::FunctionDecl * decl ) {
322        assert( nullptr != decl->stmts );
323        const auto & oldParams = getGenericParams(type);
324        assert( decl->type_params.size() == oldParams.size());
325
326        /*
327        ast::DeclReplacer::TypeMap typeMap;
328        for (auto it = oldParams.begin(), jt = decl->type_params.begin(); it != oldParams.end(); ++it, ++jt) {
329                typeMap.emplace(*it, *jt);
330        }
331
332        const ast::FunctionDecl * mut = strict_dynamic_cast<const ast::FunctionDecl *>(ast::DeclReplacer::replace(decl, typeMap));
333        assert (mut == decl);
334        */
335
336        definitions.push_back( decl );
337}
338
339/// Make a forward declaration of the decl and add it to forwards.
340void FuncGenerator::produceForwardDecl( const ast::FunctionDecl * decl ) {
341        if (0 != functionNesting) return;
342        ast::FunctionDecl * fwd =
343                ( decl->stmts ) ? ast::asForward( decl ) : ast::deepCopy( decl ) ;
344        fwd->fixUniqueId();
345        forwards.push_back( fwd );
346}
347
348void replaceAll( std::vector<ast::ptr<ast::DeclWithType>> & dwts,
349                const ast::DeclReplacer::TypeMap & map ) {
350        for ( auto & dwt : dwts ) {
351                dwt = strict_dynamic_cast<const ast::DeclWithType *>(
352                                ast::DeclReplacer::replace( dwt, map ) );
353        }
354}
355
356/// Generates a basic prototype function declaration.
357ast::FunctionDecl * FuncGenerator::genProto( std::string&& name,
358                std::vector<ast::ptr<ast::DeclWithType>>&& params,
359                std::vector<ast::ptr<ast::DeclWithType>>&& returns ) const {
360
361        // Handle generic prameters and assertions, if any.
362        auto const & old_type_params = getGenericParams( type );
363        ast::DeclReplacer::TypeMap oldToNew;
364        std::vector<ast::ptr<ast::TypeDecl>> type_params;
365        std::vector<ast::ptr<ast::DeclWithType>> assertions;
366
367        ast::DeclReplacer::TypeMap typeMap;
368        for ( auto & old_param : old_type_params ) {
369                ast::TypeDecl * decl = ast::deepCopy( old_param );
370                decl->init = nullptr;
371                splice( assertions, decl->assertions );
372                oldToNew.emplace( std::make_pair( old_param, decl ) );
373                type_params.push_back( decl );
374                typeMap.emplace(old_param, decl);
375        }
376
377        for (auto & param : params) {
378                param = ast::DeclReplacer::replace(param, typeMap);
379        }
380        for (auto & param : returns) {
381                param = ast::DeclReplacer::replace(param, typeMap);
382        }
383        replaceAll( params, oldToNew );
384        replaceAll( returns, oldToNew );
385        replaceAll( assertions, oldToNew );
386
387        ast::FunctionDecl * decl = new ast::FunctionDecl(
388                // Auto-generated routines use the type declaration's location.
389                getLocation(),
390                std::move( name ),
391                std::move( type_params ),
392                std::move( assertions ),
393                std::move( params ),
394                std::move( returns ),
395                // Only a prototype, no body.
396                nullptr,
397                // Use static storage if we are at the top level.
398                (0 < functionNesting) ? ast::Storage::Classes() : ast::Storage::Static,
399                proto_linkage,
400                std::vector<ast::ptr<ast::Attribute>>(),
401                // Auto-generated routines are inline to avoid conflicts.
402                ast::Function::Specs( ast::Function::Inline ) );
403        decl->fixUniqueId();
404        return decl;
405}
406
407ast::ObjectDecl * FuncGenerator::dstParam() const {
408        return new ast::ObjectDecl( getLocation(), "_dst",
409                new ast::ReferenceType( ast::deepCopy( type ) ) );
410}
411
412ast::ObjectDecl * FuncGenerator::srcParam() const {
413        return new ast::ObjectDecl( getLocation(), "_src",
414                ast::deepCopy( type ) );
415}
416
417/// Use the current type T to create `void ?{}(T & _dst)`.
418ast::FunctionDecl * FuncGenerator::genCtorProto() const {
419        return genProto( "?{}", { dstParam() }, {} );
420}
421
422/// Use the current type T to create `void ?{}(T & _dst, T _src)`.
423ast::FunctionDecl * FuncGenerator::genCopyProto() const {
424        return genProto( "?{}", { dstParam(), srcParam() }, {} );
425}
426
427/// Use the current type T to create `void ?{}(T & _dst)`.
428ast::FunctionDecl * FuncGenerator::genDtorProto() const {
429        // The destructor must be mutex on a concurrent type.
430        auto dst = dstParam();
431        if ( isConcurrentType() ) {
432                add_qualifiers( dst->type, ast::CV::Qualifiers( ast::CV::Mutex ) );
433        }
434        return genProto( "^?{}", { dst }, {} );
435}
436
437/// Use the current type T to create `T ?{}(T & _dst, T _src)`.
438ast::FunctionDecl * FuncGenerator::genAssignProto() const {
439        // Only the name is different, so just reuse the generation function.
440        auto retval = srcParam();
441        retval->name = "_ret";
442        return genProto( "?=?", { dstParam(), srcParam() }, { retval } );
443}
444
445// This one can return null if the last field is an unnamed bitfield.
446ast::FunctionDecl * FuncGenerator::genFieldCtorProto(
447                unsigned int fields ) const {
448        assert( 0 < fields );
449        auto aggr = strict_dynamic_cast<const ast::AggregateDecl *>( getDecl() );
450
451        std::vector<ast::ptr<ast::DeclWithType>> params = { dstParam() };
452        for ( unsigned int index = 0 ; index < fields ; ++index ) {
453                auto member = aggr->members[index].strict_as<ast::DeclWithType>();
454                if ( ast::isUnnamedBitfield(
455                                dynamic_cast<const ast::ObjectDecl *>( member ) ) ) {
456                        if ( index == fields - 1 ) {
457                                return nullptr;
458                        }
459                        continue;
460                }
461
462                auto * paramType = ast::deepCopy( member->get_type() );
463                paramType->attributes.clear();
464                ast::ObjectDecl * param = new ast::ObjectDecl(
465                        getLocation(), member->name, paramType );
466                for ( auto & attr : member->attributes ) {
467                        if ( attr->isValidOnFuncParam() ) {
468                                param->attributes.push_back( attr );
469                        }
470                }
471                params.emplace_back( param );
472        }
473        return genProto( "?{}", std::move( params ), {} );
474}
475
476void appendReturnThis( ast::FunctionDecl * decl ) {
477        assert( 1 <= decl->params.size() );
478        assert( 1 == decl->returns.size() );
479        assert( decl->stmts );
480
481        const CodeLocation& location = (decl->stmts->kids.empty())
482                ? decl->stmts->location : decl->stmts->kids.back()->location;
483        const ast::DeclWithType * thisParam = decl->params.front();
484        decl->stmts.get_and_mutate()->push_back(
485                new ast::ReturnStmt( location,
486                        new ast::VariableExpr( location, thisParam )
487                )
488        );
489}
490
491void FuncGenerator::genStandardFuncs() {
492        // The order here determines the order that these functions are generated.
493        // Assignment should come last since it uses copy constructor in return.
494        ast::FunctionDecl *(FuncGenerator::*standardProtos[4])() const = {
495                        &FuncGenerator::genCtorProto, &FuncGenerator::genCopyProto,
496                        &FuncGenerator::genDtorProto, &FuncGenerator::genAssignProto };
497        for ( auto & generator : standardProtos ) {
498                ast::FunctionDecl * decl = (this->*generator)();
499                produceForwardDecl( decl );
500                genFuncBody( decl );
501                if ( CodeGen::isAssignment( decl->name ) ) {
502                        appendReturnThis( decl );
503                }
504                produceDecl( decl );
505        }
506}
507
508void StructFuncGenerator::genFieldCtors() {
509        // The field constructors are only generated if the default constructor
510        // and copy constructor are both generated, since the need both.
511        unsigned numCtors = std::count_if( definitions.begin(), definitions.end(),
512                [](const ast::Decl * decl){ return CodeGen::isConstructor( decl->name ); }
513        );
514        if ( 2 != numCtors ) return;
515
516        for ( unsigned int num = 1 ; num <= decl->members.size() ; ++num ) {
517                ast::FunctionDecl * ctor = genFieldCtorProto( num );
518                if ( nullptr == ctor ) {
519                        continue;
520                }
521                produceForwardDecl( ctor );
522                makeFieldCtorBody( decl->members.begin(), decl->members.end(), ctor );
523                produceDecl( ctor );
524        }
525}
526
527void StructFuncGenerator::genFuncBody( ast::FunctionDecl * functionDecl ) {
528        // Generate appropriate calls to member constructors and assignment.
529        // Destructor needs to do everything in reverse,
530        // so pass "forward" based on whether the function is a destructor
531        if ( CodeGen::isDestructor( functionDecl->name ) ) {
532                makeFunctionBody( decl->members.rbegin(), decl->members.rend(),
533                        functionDecl, SymTab::LoopBackward );
534        } else {
535                makeFunctionBody( decl->members.begin(), decl->members.end(),
536                        functionDecl, SymTab::LoopForward );
537        }
538}
539
540ast::ptr<ast::Stmt> StructFuncGenerator::makeMemberOp(
541                const CodeLocation& location, const ast::ObjectDecl * dstParam,
542                const ast::Expr * src, const ast::ObjectDecl * field,
543                ast::FunctionDecl * func, SymTab::LoopDirection direction ) {
544        InitTweak::InitExpander_new srcParam( src );
545        // Assign to destination.
546        ast::MemberExpr * dstSelect = new ast::MemberExpr(
547                location,
548                field,
549                new ast::CastExpr(
550                        location,
551                        new ast::VariableExpr( location, dstParam ),
552                        dstParam->type.strict_as<ast::ReferenceType>()->base
553                )
554        );
555        return genImplicitCall(
556                srcParam, dstSelect, location, func->name,
557                field, direction
558        );
559}
560
561template<typename Iterator>
562void StructFuncGenerator::makeFunctionBody( Iterator current, Iterator end,
563                ast::FunctionDecl * func, SymTab::LoopDirection direction ) {
564        // Trying to get the best code location. Should probably use a helper or
565        // just figure out what that would be given where this is called.
566        assert( nullptr == func->stmts );
567        const CodeLocation& location = func->location;
568
569        ast::CompoundStmt * stmts = new ast::CompoundStmt( location );
570
571        for ( ; current != end ; ++current ) {
572                const ast::ptr<ast::Decl> & member = *current;
573                auto field = member.as<ast::ObjectDecl>();
574                if ( nullptr == field ) {
575                        continue;
576                }
577
578                // Don't assign to constant members (but do construct/destruct them).
579                if ( CodeGen::isAssignment( func->name ) ) {
580                        // For array types we need to strip off the array layers.
581                        const ast::Type * type = field->get_type();
582                        while ( auto at = dynamic_cast<const ast::ArrayType *>( type ) ) {
583                                type = at->base;
584                        }
585                        if ( type->is_const() ) {
586                                continue;
587                        }
588                }
589
590                assert( !func->params.empty() );
591                const ast::ObjectDecl * dstParam =
592                        func->params.front().strict_as<ast::ObjectDecl>();
593                const ast::ObjectDecl * srcParam = nullptr;
594                if ( 2 == func->params.size() ) {
595                        srcParam = func->params.back().strict_as<ast::ObjectDecl>();
596                }
597
598                ast::MemberExpr * srcSelect = (srcParam) ? new ast::MemberExpr(
599                        location, field, new ast::VariableExpr( location, srcParam )
600                ) : nullptr;
601                ast::ptr<ast::Stmt> stmt =
602                        makeMemberOp( location, dstParam, srcSelect, field, func, direction );
603
604                if ( nullptr != stmt ) {
605                        stmts->kids.push_back( stmt );
606                }
607        }
608
609        func->stmts = stmts;
610}
611
612template<typename Iterator>
613void StructFuncGenerator::makeFieldCtorBody( Iterator current, Iterator end,
614                ast::FunctionDecl * func ) {
615        const CodeLocation& location = func->location;
616        auto & params = func->params;
617        // Need at least the constructed parameter and one field parameter.
618        assert( 2 <= params.size() );
619
620        ast::CompoundStmt * stmts = new ast::CompoundStmt( location );
621
622        auto dstParam = params.front().strict_as<ast::ObjectDecl>();
623        // Skip over the 'this' parameter.
624        for ( auto param = params.begin() + 1 ; current != end ; ++current ) {
625                const ast::ptr<ast::Decl> & member = *current;
626                ast::ptr<ast::Stmt> stmt = nullptr;
627                auto field = member.as<ast::ObjectDecl>();
628                // Not sure why it could be null.
629                // Don't make a function for a parameter that is an unnamed bitfield.
630                if ( nullptr == field || ast::isUnnamedBitfield( field ) ) {
631                        continue;
632                // Matching Parameter: Initialize the field by copy.
633                } else if ( params.end() != param ) {
634                        const ast::Expr *srcSelect = new ast::VariableExpr(
635                                func->location, param->get() );
636                        stmt = makeMemberOp( location, dstParam, srcSelect, field, func, SymTab::LoopForward );
637                        ++param;
638                // No Matching Parameter: Initialize the field by default constructor.
639                } else {
640                        stmt = makeMemberOp( location, dstParam, nullptr, field, func, SymTab::LoopForward );
641                }
642
643                if ( nullptr != stmt ) {
644                        stmts->kids.push_back( stmt );
645                }
646        }
647        func->stmts = stmts;
648}
649
650void UnionFuncGenerator::genFieldCtors() {
651        // Field constructors are only generated if default and copy constructor
652        // are generated, since they need access to both
653        unsigned numCtors = std::count_if( definitions.begin(), definitions.end(),
654                []( const ast::Decl * d ){ return CodeGen::isConstructor( d->name ); }
655        );
656        if ( 2 != numCtors ) {
657                return;
658        }
659
660        // Create a constructor which takes the first member type as a
661        // parameter. For example for `union A { int x; char y; };` generate
662        // a function with signature `void ?{}(A *, int)`. This mimics C's
663        // behaviour which initializes the first member of the union.
664
665        // Still, there must be some members.
666        if ( !decl->members.empty() ) {
667                ast::FunctionDecl * ctor = genFieldCtorProto( 1 );
668                if ( nullptr == ctor ) {
669                        return;
670                }
671                produceForwardDecl( ctor );
672                auto params = ctor->params;
673                auto dstParam = params.front().strict_as<ast::ObjectDecl>();
674                auto srcParam = params.back().strict_as<ast::ObjectDecl>();
675                ctor->stmts = new ast::CompoundStmt( getLocation(),
676                        { makeAssignOp( getLocation(), dstParam, srcParam ) }
677                );
678                produceDecl( ctor );
679        }
680}
681
682void UnionFuncGenerator::genFuncBody( ast::FunctionDecl * functionDecl ) {
683        const CodeLocation& location = functionDecl->location;
684        auto & params = functionDecl->params;
685        if ( InitTweak::isCopyConstructor( functionDecl )
686                        || InitTweak::isAssignment( functionDecl ) ) {
687                assert( 2 == params.size() );
688                auto dstParam = params.front().strict_as<ast::ObjectDecl>();
689                auto srcParam = params.back().strict_as<ast::ObjectDecl>();
690                functionDecl->stmts = new ast::CompoundStmt( location,
691                        { makeAssignOp( location, dstParam, srcParam ) }
692                );
693        } else {
694                assert( 1 == params.size() );
695                // Default constructor and destructor is empty.
696                functionDecl->stmts = new ast::CompoundStmt( location );
697                // Add unused attribute to parameter to silence warnings.
698                addUnusedAttribute( params.front() );
699
700                // Just an extra step to make the forward and declaration match.
701                if ( forwards.empty() ) return;
702                ast::FunctionDecl * fwd = strict_dynamic_cast<ast::FunctionDecl *>(
703                        forwards.back().get_and_mutate() );
704                addUnusedAttribute( fwd->params.front() );
705        }
706}
707
708ast::ExprStmt * UnionFuncGenerator::makeAssignOp( const CodeLocation& location,
709                const ast::ObjectDecl * dstParam, const ast::ObjectDecl * srcParam ) {
710        return new ast::ExprStmt( location, new ast::UntypedExpr(
711                location,
712                new ast::NameExpr( location, "__builtin_memcpy" ),
713                {
714                        new ast::AddressExpr( location,
715                                new ast::VariableExpr( location, dstParam ) ),
716                        new ast::AddressExpr( location,
717                                new ast::VariableExpr( location, srcParam ) ),
718                        new ast::SizeofExpr( location, srcParam->type ),
719                } ) );
720}
721
722void EnumFuncGenerator::genFieldCtors() {
723        // Enumerations to not have field constructors.
724}
725
726void EnumFuncGenerator::genFuncBody( ast::FunctionDecl * functionDecl ) {
727        const CodeLocation& location = functionDecl->location;
728        auto & params = functionDecl->params;
729        if ( InitTweak::isCopyConstructor( functionDecl )
730                        || InitTweak::isAssignment( functionDecl ) ) {
731                assert( 2 == params.size() );
732                auto dstParam = params.front().strict_as<ast::ObjectDecl>();
733                auto srcParam = params.back().strict_as<ast::ObjectDecl>();
734
735                /* This looks like a recursive call, but code-gen will turn it into
736                 * a C-style assignment.
737                 *
738                 * This is still before function pointer type conversion,
739                 * so this will have to do it manually.
740                 *
741                 * It will also reference the parent function declaration, creating
742                 * a cycle for references. This also means that the ref-counts are
743                 * now non-zero and the declaration will be deleted if it ever
744                 * returns to zero.
745                 */
746                auto callExpr = new ast::ApplicationExpr( location,
747                        ast::VariableExpr::functionPointer( location, functionDecl ),
748                        {
749                                new ast::VariableExpr( location, dstParam ),
750                                new ast::VariableExpr( location, srcParam ),
751                        }
752                );
753                functionDecl->stmts = new ast::CompoundStmt( location,
754                        { new ast::ExprStmt( location, callExpr ) }
755                );
756        } else {
757                assert( 1 == params.size() );
758                // Default constructor and destructor is empty.
759                functionDecl->stmts = new ast::CompoundStmt( location );
760                // Just add unused attribute to parameter to silence warnings.
761                addUnusedAttribute( params.front() );
762
763                // Just an extra step to make the forward and declaration match.
764                if ( forwards.empty() ) return;
765                ast::FunctionDecl * fwd = strict_dynamic_cast<ast::FunctionDecl *>(
766                        forwards.back().get_and_mutate() );
767                addUnusedAttribute( fwd->params.front() );
768        }
769}
770
771void TypeFuncGenerator::genFieldCtors() {
772        // Opaque types do not have field constructors.
773}
774
775void TypeFuncGenerator::genFuncBody( ast::FunctionDecl * functionDecl ) {
776        const CodeLocation& location = functionDecl->location;
777        auto & params = functionDecl->type->params;
778        assertf( 1 == params.size() || 2 == params.size(),
779                "Incorrect number of parameters in autogenerated typedecl function: %zd",
780                params.size() );
781        auto dstParam = params.front().strict_as<ast::ObjectDecl>();
782        auto srcParam = (2 == params.size())
783                ? params.back().strict_as<ast::ObjectDecl>() : nullptr;
784        // Generate appropriate calls to member constructor and assignment.
785        ast::UntypedExpr * expr = new ast::UntypedExpr( location,
786                new ast::NameExpr( location, functionDecl->name )
787        );
788        expr->args.push_back( new ast::CastExpr( location,
789                new ast::VariableExpr( location, dstParam ),
790                new ast::ReferenceType( decl->base )
791        ) );
792        if ( srcParam ) {
793                expr->args.push_back( new ast::CastExpr( location,
794                        new ast::VariableExpr( location, srcParam ),
795                        decl->base
796                ) );
797        }
798        functionDecl->stmts = new ast::CompoundStmt( location,
799                { new ast::ExprStmt( location, expr ) }
800        );
801}
802
803} // namespace
804
805void autogenerateRoutines( ast::TranslationUnit & translationUnit ) {
806        ast::Pass<AutogenerateRoutines_new>::run( translationUnit );
807}
808
809} // Validate
810
811// Local Variables: //
812// tab-width: 4 //
813// mode: c++ //
814// compile-command: "make install" //
815// End: //
Note: See TracBrowser for help on using the repository browser.